Annotation of imach/src/imach.c, revision 1.151

1.151   ! brouard     1: /* $Id: imach.c,v 1.150 2014/06/18 16:42:35 brouard Exp $
1.126     brouard     2:   $State: Exp $
                      3:   $Log: imach.c,v $
1.151   ! brouard     4:   Revision 1.150  2014/06/18 16:42:35  brouard
        !             5:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
        !             6:   Author: brouard
        !             7: 
1.150     brouard     8:   Revision 1.149  2014/06/18 15:51:14  brouard
                      9:   Summary: Some fixes in parameter files errors
                     10:   Author: Nicolas Brouard
                     11: 
1.149     brouard    12:   Revision 1.148  2014/06/17 17:38:48  brouard
                     13:   Summary: Nothing new
                     14:   Author: Brouard
                     15: 
                     16:   Just a new packaging for OS/X version 0.98nS
                     17: 
1.148     brouard    18:   Revision 1.147  2014/06/16 10:33:11  brouard
                     19:   *** empty log message ***
                     20: 
1.147     brouard    21:   Revision 1.146  2014/06/16 10:20:28  brouard
                     22:   Summary: Merge
                     23:   Author: Brouard
                     24: 
                     25:   Merge, before building revised version.
                     26: 
1.146     brouard    27:   Revision 1.145  2014/06/10 21:23:15  brouard
                     28:   Summary: Debugging with valgrind
                     29:   Author: Nicolas Brouard
                     30: 
                     31:   Lot of changes in order to output the results with some covariates
                     32:   After the Edimburgh REVES conference 2014, it seems mandatory to
                     33:   improve the code.
                     34:   No more memory valgrind error but a lot has to be done in order to
                     35:   continue the work of splitting the code into subroutines.
                     36:   Also, decodemodel has been improved. Tricode is still not
                     37:   optimal. nbcode should be improved. Documentation has been added in
                     38:   the source code.
                     39: 
1.144     brouard    40:   Revision 1.143  2014/01/26 09:45:38  brouard
                     41:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                     42: 
                     43:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                     44:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                     45: 
1.143     brouard    46:   Revision 1.142  2014/01/26 03:57:36  brouard
                     47:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                     48: 
                     49:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                     50: 
1.142     brouard    51:   Revision 1.141  2014/01/26 02:42:01  brouard
                     52:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                     53: 
1.141     brouard    54:   Revision 1.140  2011/09/02 10:37:54  brouard
                     55:   Summary: times.h is ok with mingw32 now.
                     56: 
1.140     brouard    57:   Revision 1.139  2010/06/14 07:50:17  brouard
                     58:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                     59:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                     60: 
1.139     brouard    61:   Revision 1.138  2010/04/30 18:19:40  brouard
                     62:   *** empty log message ***
                     63: 
1.138     brouard    64:   Revision 1.137  2010/04/29 18:11:38  brouard
                     65:   (Module): Checking covariates for more complex models
                     66:   than V1+V2. A lot of change to be done. Unstable.
                     67: 
1.137     brouard    68:   Revision 1.136  2010/04/26 20:30:53  brouard
                     69:   (Module): merging some libgsl code. Fixing computation
                     70:   of likelione (using inter/intrapolation if mle = 0) in order to
                     71:   get same likelihood as if mle=1.
                     72:   Some cleaning of code and comments added.
                     73: 
1.136     brouard    74:   Revision 1.135  2009/10/29 15:33:14  brouard
                     75:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                     76: 
1.135     brouard    77:   Revision 1.134  2009/10/29 13:18:53  brouard
                     78:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                     79: 
1.134     brouard    80:   Revision 1.133  2009/07/06 10:21:25  brouard
                     81:   just nforces
                     82: 
1.133     brouard    83:   Revision 1.132  2009/07/06 08:22:05  brouard
                     84:   Many tings
                     85: 
1.132     brouard    86:   Revision 1.131  2009/06/20 16:22:47  brouard
                     87:   Some dimensions resccaled
                     88: 
1.131     brouard    89:   Revision 1.130  2009/05/26 06:44:34  brouard
                     90:   (Module): Max Covariate is now set to 20 instead of 8. A
                     91:   lot of cleaning with variables initialized to 0. Trying to make
                     92:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                     93: 
1.130     brouard    94:   Revision 1.129  2007/08/31 13:49:27  lievre
                     95:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                     96: 
1.129     lievre     97:   Revision 1.128  2006/06/30 13:02:05  brouard
                     98:   (Module): Clarifications on computing e.j
                     99: 
1.128     brouard   100:   Revision 1.127  2006/04/28 18:11:50  brouard
                    101:   (Module): Yes the sum of survivors was wrong since
                    102:   imach-114 because nhstepm was no more computed in the age
                    103:   loop. Now we define nhstepma in the age loop.
                    104:   (Module): In order to speed up (in case of numerous covariates) we
                    105:   compute health expectancies (without variances) in a first step
                    106:   and then all the health expectancies with variances or standard
                    107:   deviation (needs data from the Hessian matrices) which slows the
                    108:   computation.
                    109:   In the future we should be able to stop the program is only health
                    110:   expectancies and graph are needed without standard deviations.
                    111: 
1.127     brouard   112:   Revision 1.126  2006/04/28 17:23:28  brouard
                    113:   (Module): Yes the sum of survivors was wrong since
                    114:   imach-114 because nhstepm was no more computed in the age
                    115:   loop. Now we define nhstepma in the age loop.
                    116:   Version 0.98h
                    117: 
1.126     brouard   118:   Revision 1.125  2006/04/04 15:20:31  lievre
                    119:   Errors in calculation of health expectancies. Age was not initialized.
                    120:   Forecasting file added.
                    121: 
                    122:   Revision 1.124  2006/03/22 17:13:53  lievre
                    123:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    124:   The log-likelihood is printed in the log file
                    125: 
                    126:   Revision 1.123  2006/03/20 10:52:43  brouard
                    127:   * imach.c (Module): <title> changed, corresponds to .htm file
                    128:   name. <head> headers where missing.
                    129: 
                    130:   * imach.c (Module): Weights can have a decimal point as for
                    131:   English (a comma might work with a correct LC_NUMERIC environment,
                    132:   otherwise the weight is truncated).
                    133:   Modification of warning when the covariates values are not 0 or
                    134:   1.
                    135:   Version 0.98g
                    136: 
                    137:   Revision 1.122  2006/03/20 09:45:41  brouard
                    138:   (Module): Weights can have a decimal point as for
                    139:   English (a comma might work with a correct LC_NUMERIC environment,
                    140:   otherwise the weight is truncated).
                    141:   Modification of warning when the covariates values are not 0 or
                    142:   1.
                    143:   Version 0.98g
                    144: 
                    145:   Revision 1.121  2006/03/16 17:45:01  lievre
                    146:   * imach.c (Module): Comments concerning covariates added
                    147: 
                    148:   * imach.c (Module): refinements in the computation of lli if
                    149:   status=-2 in order to have more reliable computation if stepm is
                    150:   not 1 month. Version 0.98f
                    151: 
                    152:   Revision 1.120  2006/03/16 15:10:38  lievre
                    153:   (Module): refinements in the computation of lli if
                    154:   status=-2 in order to have more reliable computation if stepm is
                    155:   not 1 month. Version 0.98f
                    156: 
                    157:   Revision 1.119  2006/03/15 17:42:26  brouard
                    158:   (Module): Bug if status = -2, the loglikelihood was
                    159:   computed as likelihood omitting the logarithm. Version O.98e
                    160: 
                    161:   Revision 1.118  2006/03/14 18:20:07  brouard
                    162:   (Module): varevsij Comments added explaining the second
                    163:   table of variances if popbased=1 .
                    164:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    165:   (Module): Function pstamp added
                    166:   (Module): Version 0.98d
                    167: 
                    168:   Revision 1.117  2006/03/14 17:16:22  brouard
                    169:   (Module): varevsij Comments added explaining the second
                    170:   table of variances if popbased=1 .
                    171:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    172:   (Module): Function pstamp added
                    173:   (Module): Version 0.98d
                    174: 
                    175:   Revision 1.116  2006/03/06 10:29:27  brouard
                    176:   (Module): Variance-covariance wrong links and
                    177:   varian-covariance of ej. is needed (Saito).
                    178: 
                    179:   Revision 1.115  2006/02/27 12:17:45  brouard
                    180:   (Module): One freematrix added in mlikeli! 0.98c
                    181: 
                    182:   Revision 1.114  2006/02/26 12:57:58  brouard
                    183:   (Module): Some improvements in processing parameter
                    184:   filename with strsep.
                    185: 
                    186:   Revision 1.113  2006/02/24 14:20:24  brouard
                    187:   (Module): Memory leaks checks with valgrind and:
                    188:   datafile was not closed, some imatrix were not freed and on matrix
                    189:   allocation too.
                    190: 
                    191:   Revision 1.112  2006/01/30 09:55:26  brouard
                    192:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    193: 
                    194:   Revision 1.111  2006/01/25 20:38:18  brouard
                    195:   (Module): Lots of cleaning and bugs added (Gompertz)
                    196:   (Module): Comments can be added in data file. Missing date values
                    197:   can be a simple dot '.'.
                    198: 
                    199:   Revision 1.110  2006/01/25 00:51:50  brouard
                    200:   (Module): Lots of cleaning and bugs added (Gompertz)
                    201: 
                    202:   Revision 1.109  2006/01/24 19:37:15  brouard
                    203:   (Module): Comments (lines starting with a #) are allowed in data.
                    204: 
                    205:   Revision 1.108  2006/01/19 18:05:42  lievre
                    206:   Gnuplot problem appeared...
                    207:   To be fixed
                    208: 
                    209:   Revision 1.107  2006/01/19 16:20:37  brouard
                    210:   Test existence of gnuplot in imach path
                    211: 
                    212:   Revision 1.106  2006/01/19 13:24:36  brouard
                    213:   Some cleaning and links added in html output
                    214: 
                    215:   Revision 1.105  2006/01/05 20:23:19  lievre
                    216:   *** empty log message ***
                    217: 
                    218:   Revision 1.104  2005/09/30 16:11:43  lievre
                    219:   (Module): sump fixed, loop imx fixed, and simplifications.
                    220:   (Module): If the status is missing at the last wave but we know
                    221:   that the person is alive, then we can code his/her status as -2
                    222:   (instead of missing=-1 in earlier versions) and his/her
                    223:   contributions to the likelihood is 1 - Prob of dying from last
                    224:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    225:   the healthy state at last known wave). Version is 0.98
                    226: 
                    227:   Revision 1.103  2005/09/30 15:54:49  lievre
                    228:   (Module): sump fixed, loop imx fixed, and simplifications.
                    229: 
                    230:   Revision 1.102  2004/09/15 17:31:30  brouard
                    231:   Add the possibility to read data file including tab characters.
                    232: 
                    233:   Revision 1.101  2004/09/15 10:38:38  brouard
                    234:   Fix on curr_time
                    235: 
                    236:   Revision 1.100  2004/07/12 18:29:06  brouard
                    237:   Add version for Mac OS X. Just define UNIX in Makefile
                    238: 
                    239:   Revision 1.99  2004/06/05 08:57:40  brouard
                    240:   *** empty log message ***
                    241: 
                    242:   Revision 1.98  2004/05/16 15:05:56  brouard
                    243:   New version 0.97 . First attempt to estimate force of mortality
                    244:   directly from the data i.e. without the need of knowing the health
                    245:   state at each age, but using a Gompertz model: log u =a + b*age .
                    246:   This is the basic analysis of mortality and should be done before any
                    247:   other analysis, in order to test if the mortality estimated from the
                    248:   cross-longitudinal survey is different from the mortality estimated
                    249:   from other sources like vital statistic data.
                    250: 
                    251:   The same imach parameter file can be used but the option for mle should be -3.
                    252: 
1.133     brouard   253:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   254:   former routines in order to include the new code within the former code.
                    255: 
                    256:   The output is very simple: only an estimate of the intercept and of
                    257:   the slope with 95% confident intervals.
                    258: 
                    259:   Current limitations:
                    260:   A) Even if you enter covariates, i.e. with the
                    261:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    262:   B) There is no computation of Life Expectancy nor Life Table.
                    263: 
                    264:   Revision 1.97  2004/02/20 13:25:42  lievre
                    265:   Version 0.96d. Population forecasting command line is (temporarily)
                    266:   suppressed.
                    267: 
                    268:   Revision 1.96  2003/07/15 15:38:55  brouard
                    269:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    270:   rewritten within the same printf. Workaround: many printfs.
                    271: 
                    272:   Revision 1.95  2003/07/08 07:54:34  brouard
                    273:   * imach.c (Repository):
                    274:   (Repository): Using imachwizard code to output a more meaningful covariance
                    275:   matrix (cov(a12,c31) instead of numbers.
                    276: 
                    277:   Revision 1.94  2003/06/27 13:00:02  brouard
                    278:   Just cleaning
                    279: 
                    280:   Revision 1.93  2003/06/25 16:33:55  brouard
                    281:   (Module): On windows (cygwin) function asctime_r doesn't
                    282:   exist so I changed back to asctime which exists.
                    283:   (Module): Version 0.96b
                    284: 
                    285:   Revision 1.92  2003/06/25 16:30:45  brouard
                    286:   (Module): On windows (cygwin) function asctime_r doesn't
                    287:   exist so I changed back to asctime which exists.
                    288: 
                    289:   Revision 1.91  2003/06/25 15:30:29  brouard
                    290:   * imach.c (Repository): Duplicated warning errors corrected.
                    291:   (Repository): Elapsed time after each iteration is now output. It
                    292:   helps to forecast when convergence will be reached. Elapsed time
                    293:   is stamped in powell.  We created a new html file for the graphs
                    294:   concerning matrix of covariance. It has extension -cov.htm.
                    295: 
                    296:   Revision 1.90  2003/06/24 12:34:15  brouard
                    297:   (Module): Some bugs corrected for windows. Also, when
                    298:   mle=-1 a template is output in file "or"mypar.txt with the design
                    299:   of the covariance matrix to be input.
                    300: 
                    301:   Revision 1.89  2003/06/24 12:30:52  brouard
                    302:   (Module): Some bugs corrected for windows. Also, when
                    303:   mle=-1 a template is output in file "or"mypar.txt with the design
                    304:   of the covariance matrix to be input.
                    305: 
                    306:   Revision 1.88  2003/06/23 17:54:56  brouard
                    307:   * 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.
                    308: 
                    309:   Revision 1.87  2003/06/18 12:26:01  brouard
                    310:   Version 0.96
                    311: 
                    312:   Revision 1.86  2003/06/17 20:04:08  brouard
                    313:   (Module): Change position of html and gnuplot routines and added
                    314:   routine fileappend.
                    315: 
                    316:   Revision 1.85  2003/06/17 13:12:43  brouard
                    317:   * imach.c (Repository): Check when date of death was earlier that
                    318:   current date of interview. It may happen when the death was just
                    319:   prior to the death. In this case, dh was negative and likelihood
                    320:   was wrong (infinity). We still send an "Error" but patch by
                    321:   assuming that the date of death was just one stepm after the
                    322:   interview.
                    323:   (Repository): Because some people have very long ID (first column)
                    324:   we changed int to long in num[] and we added a new lvector for
                    325:   memory allocation. But we also truncated to 8 characters (left
                    326:   truncation)
                    327:   (Repository): No more line truncation errors.
                    328: 
                    329:   Revision 1.84  2003/06/13 21:44:43  brouard
                    330:   * imach.c (Repository): Replace "freqsummary" at a correct
                    331:   place. It differs from routine "prevalence" which may be called
                    332:   many times. Probs is memory consuming and must be used with
                    333:   parcimony.
                    334:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    335: 
                    336:   Revision 1.83  2003/06/10 13:39:11  lievre
                    337:   *** empty log message ***
                    338: 
                    339:   Revision 1.82  2003/06/05 15:57:20  brouard
                    340:   Add log in  imach.c and  fullversion number is now printed.
                    341: 
                    342: */
                    343: /*
                    344:    Interpolated Markov Chain
                    345: 
                    346:   Short summary of the programme:
                    347:   
                    348:   This program computes Healthy Life Expectancies from
                    349:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    350:   first survey ("cross") where individuals from different ages are
                    351:   interviewed on their health status or degree of disability (in the
                    352:   case of a health survey which is our main interest) -2- at least a
                    353:   second wave of interviews ("longitudinal") which measure each change
                    354:   (if any) in individual health status.  Health expectancies are
                    355:   computed from the time spent in each health state according to a
                    356:   model. More health states you consider, more time is necessary to reach the
                    357:   Maximum Likelihood of the parameters involved in the model.  The
                    358:   simplest model is the multinomial logistic model where pij is the
                    359:   probability to be observed in state j at the second wave
                    360:   conditional to be observed in state i at the first wave. Therefore
                    361:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    362:   'age' is age and 'sex' is a covariate. If you want to have a more
                    363:   complex model than "constant and age", you should modify the program
                    364:   where the markup *Covariates have to be included here again* invites
                    365:   you to do it.  More covariates you add, slower the
                    366:   convergence.
                    367: 
                    368:   The advantage of this computer programme, compared to a simple
                    369:   multinomial logistic model, is clear when the delay between waves is not
                    370:   identical for each individual. Also, if a individual missed an
                    371:   intermediate interview, the information is lost, but taken into
                    372:   account using an interpolation or extrapolation.  
                    373: 
                    374:   hPijx is the probability to be observed in state i at age x+h
                    375:   conditional to the observed state i at age x. The delay 'h' can be
                    376:   split into an exact number (nh*stepm) of unobserved intermediate
                    377:   states. This elementary transition (by month, quarter,
                    378:   semester or year) is modelled as a multinomial logistic.  The hPx
                    379:   matrix is simply the matrix product of nh*stepm elementary matrices
                    380:   and the contribution of each individual to the likelihood is simply
                    381:   hPijx.
                    382: 
                    383:   Also this programme outputs the covariance matrix of the parameters but also
                    384:   of the life expectancies. It also computes the period (stable) prevalence. 
                    385:   
1.133     brouard   386:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    387:            Institut national d'études démographiques, Paris.
1.126     brouard   388:   This software have been partly granted by Euro-REVES, a concerted action
                    389:   from the European Union.
                    390:   It is copyrighted identically to a GNU software product, ie programme and
                    391:   software can be distributed freely for non commercial use. Latest version
                    392:   can be accessed at http://euroreves.ined.fr/imach .
                    393: 
                    394:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    395:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    396:   
                    397:   **********************************************************************/
                    398: /*
                    399:   main
                    400:   read parameterfile
                    401:   read datafile
                    402:   concatwav
                    403:   freqsummary
                    404:   if (mle >= 1)
                    405:     mlikeli
                    406:   print results files
                    407:   if mle==1 
                    408:      computes hessian
                    409:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    410:       begin-prev-date,...
                    411:   open gnuplot file
                    412:   open html file
1.145     brouard   413:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    414:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    415:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    416:     freexexit2 possible for memory heap.
                    417: 
                    418:   h Pij x                         | pij_nom  ficrestpij
                    419:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    420:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    421:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    422: 
                    423:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    424:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    425:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    426:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    427:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    428: 
1.126     brouard   429:   forecasting if prevfcast==1 prevforecast call prevalence()
                    430:   health expectancies
                    431:   Variance-covariance of DFLE
                    432:   prevalence()
                    433:    movingaverage()
                    434:   varevsij() 
                    435:   if popbased==1 varevsij(,popbased)
                    436:   total life expectancies
                    437:   Variance of period (stable) prevalence
                    438:  end
                    439: */
                    440: 
                    441: 
                    442: 
                    443:  
                    444: #include <math.h>
                    445: #include <stdio.h>
                    446: #include <stdlib.h>
                    447: #include <string.h>
                    448: #include <unistd.h>
                    449: 
                    450: #include <limits.h>
                    451: #include <sys/types.h>
                    452: #include <sys/stat.h>
                    453: #include <errno.h>
                    454: extern int errno;
                    455: 
1.141     brouard   456: #ifdef LINUX
1.126     brouard   457: #include <time.h>
                    458: #include "timeval.h"
1.141     brouard   459: #else
                    460: #include <sys/time.h>
                    461: #endif
1.126     brouard   462: 
1.136     brouard   463: #ifdef GSL
                    464: #include <gsl/gsl_errno.h>
                    465: #include <gsl/gsl_multimin.h>
                    466: #endif
                    467: 
1.126     brouard   468: /* #include <libintl.h> */
                    469: /* #define _(String) gettext (String) */
                    470: 
1.141     brouard   471: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   472: 
                    473: #define GNUPLOTPROGRAM "gnuplot"
                    474: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    475: #define FILENAMELENGTH 132
                    476: 
                    477: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    478: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    479: 
1.144     brouard   480: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    481: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   482: 
                    483: #define NINTERVMAX 8
1.144     brouard   484: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    485: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    486: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145     brouard   487: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
1.126     brouard   488: #define MAXN 20000
1.144     brouard   489: #define YEARM 12. /**< Number of months per year */
1.126     brouard   490: #define AGESUP 130
                    491: #define AGEBASE 40
1.144     brouard   492: #define AGEGOMP 10. /**< Minimal age for Gompertz adjustment */
1.126     brouard   493: #ifdef UNIX
                    494: #define DIRSEPARATOR '/'
                    495: #define CHARSEPARATOR "/"
                    496: #define ODIRSEPARATOR '\\'
                    497: #else
                    498: #define DIRSEPARATOR '\\'
                    499: #define CHARSEPARATOR "\\"
                    500: #define ODIRSEPARATOR '/'
                    501: #endif
                    502: 
1.151   ! brouard   503: /* $Id: imach.c,v 1.150 2014/06/18 16:42:35 brouard Exp $ */
1.126     brouard   504: /* $State: Exp $ */
                    505: 
1.149     brouard   506: char version[]="Imach version 0.98nT, January 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121)";
1.151   ! brouard   507: char fullversion[]="$Revision: 1.150 $ $Date: 2014/06/18 16:42:35 $"; 
1.126     brouard   508: char strstart[80];
                    509: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   510: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.133     brouard   511: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145     brouard   512: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    513: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    514: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    515: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    516: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    517: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    518: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    519: int cptcov=0; /* Working variable */
1.126     brouard   520: int npar=NPARMAX;
                    521: int nlstate=2; /* Number of live states */
                    522: int ndeath=1; /* Number of dead states */
1.130     brouard   523: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   524: int popbased=0;
                    525: 
                    526: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   527: int maxwav=0; /* Maxim number of waves */
                    528: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    529: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    530: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   531:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   532: int mle=1, weightopt=0;
1.126     brouard   533: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    534: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    535: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    536:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.130     brouard   537: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   538: double **matprod2(); /* test */
1.126     brouard   539: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    540: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   541: /*FILE *fic ; */ /* Used in readdata only */
                    542: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   543: FILE *ficlog, *ficrespow;
1.130     brouard   544: int globpr=0; /* Global variable for printing or not */
1.126     brouard   545: double fretone; /* Only one call to likelihood */
1.130     brouard   546: long ipmx=0; /* Number of contributions */
1.126     brouard   547: double sw; /* Sum of weights */
                    548: char filerespow[FILENAMELENGTH];
                    549: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    550: FILE *ficresilk;
                    551: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    552: FILE *ficresprobmorprev;
                    553: FILE *fichtm, *fichtmcov; /* Html File */
                    554: FILE *ficreseij;
                    555: char filerese[FILENAMELENGTH];
                    556: FILE *ficresstdeij;
                    557: char fileresstde[FILENAMELENGTH];
                    558: FILE *ficrescveij;
                    559: char filerescve[FILENAMELENGTH];
                    560: FILE  *ficresvij;
                    561: char fileresv[FILENAMELENGTH];
                    562: FILE  *ficresvpl;
                    563: char fileresvpl[FILENAMELENGTH];
                    564: char title[MAXLINE];
                    565: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    566: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    567: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    568: char command[FILENAMELENGTH];
                    569: int  outcmd=0;
                    570: 
                    571: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                    572: 
                    573: char filelog[FILENAMELENGTH]; /* Log file */
                    574: char filerest[FILENAMELENGTH];
                    575: char fileregp[FILENAMELENGTH];
                    576: char popfile[FILENAMELENGTH];
                    577: 
                    578: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    579: 
                    580: struct timeval start_time, end_time, curr_time, last_time, forecast_time;
                    581: struct timezone tzp;
                    582: extern int gettimeofday();
                    583: struct tm tmg, tm, tmf, *gmtime(), *localtime();
                    584: long time_value;
                    585: extern long time();
                    586: char strcurr[80], strfor[80];
                    587: 
                    588: char *endptr;
                    589: long lval;
                    590: double dval;
                    591: 
                    592: #define NR_END 1
                    593: #define FREE_ARG char*
                    594: #define FTOL 1.0e-10
                    595: 
                    596: #define NRANSI 
                    597: #define ITMAX 200 
                    598: 
                    599: #define TOL 2.0e-4 
                    600: 
                    601: #define CGOLD 0.3819660 
                    602: #define ZEPS 1.0e-10 
                    603: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    604: 
                    605: #define GOLD 1.618034 
                    606: #define GLIMIT 100.0 
                    607: #define TINY 1.0e-20 
                    608: 
                    609: static double maxarg1,maxarg2;
                    610: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    611: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    612:   
                    613: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    614: #define rint(a) floor(a+0.5)
                    615: 
                    616: static double sqrarg;
                    617: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    618: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    619: int agegomp= AGEGOMP;
                    620: 
                    621: int imx; 
                    622: int stepm=1;
                    623: /* Stepm, step in month: minimum step interpolation*/
                    624: 
                    625: int estepm;
                    626: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    627: 
                    628: int m,nb;
                    629: long *num;
                    630: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
                    631: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    632: double **pmmij, ***probs;
                    633: double *ageexmed,*agecens;
                    634: double dateintmean=0;
                    635: 
                    636: double *weight;
                    637: int **s; /* Status */
1.141     brouard   638: double *agedc;
1.145     brouard   639: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   640:                  * covar=matrix(0,NCOVMAX,1,n); 
                    641:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
                    642: double  idx; 
                    643: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145     brouard   644: int *Ndum; /** Freq of modality (tricode */
1.141     brouard   645: int **codtab; /**< codtab=imatrix(1,100,1,10); */
                    646: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   647: double *lsurv, *lpop, *tpop;
                    648: 
1.143     brouard   649: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    650: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   651: 
                    652: /**************** split *************************/
                    653: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    654: {
                    655:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    656:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    657:   */ 
                    658:   char *ss;                            /* pointer */
                    659:   int  l1, l2;                         /* length counters */
                    660: 
                    661:   l1 = strlen(path );                  /* length of path */
                    662:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    663:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    664:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    665:     strcpy( name, path );              /* we got the fullname name because no directory */
                    666:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    667:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    668:     /* get current working directory */
                    669:     /*    extern  char* getcwd ( char *buf , int len);*/
                    670:     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    671:       return( GLOCK_ERROR_GETCWD );
                    672:     }
                    673:     /* got dirc from getcwd*/
                    674:     printf(" DIRC = %s \n",dirc);
                    675:   } else {                             /* strip direcotry from path */
                    676:     ss++;                              /* after this, the filename */
                    677:     l2 = strlen( ss );                 /* length of filename */
                    678:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    679:     strcpy( name, ss );                /* save file name */
                    680:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
                    681:     dirc[l1-l2] = 0;                   /* add zero */
                    682:     printf(" DIRC2 = %s \n",dirc);
                    683:   }
                    684:   /* We add a separator at the end of dirc if not exists */
                    685:   l1 = strlen( dirc );                 /* length of directory */
                    686:   if( dirc[l1-1] != DIRSEPARATOR ){
                    687:     dirc[l1] =  DIRSEPARATOR;
                    688:     dirc[l1+1] = 0; 
                    689:     printf(" DIRC3 = %s \n",dirc);
                    690:   }
                    691:   ss = strrchr( name, '.' );           /* find last / */
                    692:   if (ss >0){
                    693:     ss++;
                    694:     strcpy(ext,ss);                    /* save extension */
                    695:     l1= strlen( name);
                    696:     l2= strlen(ss)+1;
                    697:     strncpy( finame, name, l1-l2);
                    698:     finame[l1-l2]= 0;
                    699:   }
                    700: 
                    701:   return( 0 );                         /* we're done */
                    702: }
                    703: 
                    704: 
                    705: /******************************************/
                    706: 
                    707: void replace_back_to_slash(char *s, char*t)
                    708: {
                    709:   int i;
                    710:   int lg=0;
                    711:   i=0;
                    712:   lg=strlen(t);
                    713:   for(i=0; i<= lg; i++) {
                    714:     (s[i] = t[i]);
                    715:     if (t[i]== '\\') s[i]='/';
                    716:   }
                    717: }
                    718: 
1.132     brouard   719: char *trimbb(char *out, char *in)
1.137     brouard   720: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   721:   char *s;
                    722:   s=out;
                    723:   while (*in != '\0'){
1.137     brouard   724:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   725:       in++;
                    726:     }
                    727:     *out++ = *in++;
                    728:   }
                    729:   *out='\0';
                    730:   return s;
                    731: }
                    732: 
1.145     brouard   733: char *cutl(char *blocc, char *alocc, char *in, char occ)
                    734: {
                    735:   /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ' 
                    736:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                    737:      gives blocc="abcdef2ghi" and alocc="j".
                    738:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                    739:   */
                    740:   char *s, *t, *bl;
                    741:   t=in;s=in;
                    742:   while ((*in != occ) && (*in != '\0')){
                    743:     *alocc++ = *in++;
                    744:   }
                    745:   if( *in == occ){
                    746:     *(alocc)='\0';
                    747:     s=++in;
                    748:   }
                    749:  
                    750:   if (s == t) {/* occ not found */
                    751:     *(alocc-(in-s))='\0';
                    752:     in=s;
                    753:   }
                    754:   while ( *in != '\0'){
                    755:     *blocc++ = *in++;
                    756:   }
                    757: 
                    758:   *blocc='\0';
                    759:   return t;
                    760: }
1.137     brouard   761: char *cutv(char *blocc, char *alocc, char *in, char occ)
                    762: {
                    763:   /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 
                    764:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                    765:      gives blocc="abcdef2ghi" and alocc="j".
                    766:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                    767:   */
                    768:   char *s, *t;
                    769:   t=in;s=in;
                    770:   while (*in != '\0'){
                    771:     while( *in == occ){
                    772:       *blocc++ = *in++;
                    773:       s=in;
                    774:     }
                    775:     *blocc++ = *in++;
                    776:   }
                    777:   if (s == t) /* occ not found */
                    778:     *(blocc-(in-s))='\0';
                    779:   else
                    780:     *(blocc-(in-s)-1)='\0';
                    781:   in=s;
                    782:   while ( *in != '\0'){
                    783:     *alocc++ = *in++;
                    784:   }
                    785: 
                    786:   *alocc='\0';
                    787:   return s;
                    788: }
                    789: 
1.126     brouard   790: int nbocc(char *s, char occ)
                    791: {
                    792:   int i,j=0;
                    793:   int lg=20;
                    794:   i=0;
                    795:   lg=strlen(s);
                    796:   for(i=0; i<= lg; i++) {
                    797:   if  (s[i] == occ ) j++;
                    798:   }
                    799:   return j;
                    800: }
                    801: 
1.137     brouard   802: /* void cutv(char *u,char *v, char*t, char occ) */
                    803: /* { */
                    804: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                    805: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                    806: /*      gives u="abcdef2ghi" and v="j" *\/ */
                    807: /*   int i,lg,j,p=0; */
                    808: /*   i=0; */
                    809: /*   lg=strlen(t); */
                    810: /*   for(j=0; j<=lg-1; j++) { */
                    811: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                    812: /*   } */
1.126     brouard   813: 
1.137     brouard   814: /*   for(j=0; j<p; j++) { */
                    815: /*     (u[j] = t[j]); */
                    816: /*   } */
                    817: /*      u[p]='\0'; */
1.126     brouard   818: 
1.137     brouard   819: /*    for(j=0; j<= lg; j++) { */
                    820: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                    821: /*   } */
                    822: /* } */
1.126     brouard   823: 
                    824: /********************** nrerror ********************/
                    825: 
                    826: void nrerror(char error_text[])
                    827: {
                    828:   fprintf(stderr,"ERREUR ...\n");
                    829:   fprintf(stderr,"%s\n",error_text);
                    830:   exit(EXIT_FAILURE);
                    831: }
                    832: /*********************** vector *******************/
                    833: double *vector(int nl, int nh)
                    834: {
                    835:   double *v;
                    836:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                    837:   if (!v) nrerror("allocation failure in vector");
                    838:   return v-nl+NR_END;
                    839: }
                    840: 
                    841: /************************ free vector ******************/
                    842: void free_vector(double*v, int nl, int nh)
                    843: {
                    844:   free((FREE_ARG)(v+nl-NR_END));
                    845: }
                    846: 
                    847: /************************ivector *******************************/
                    848: int *ivector(long nl,long nh)
                    849: {
                    850:   int *v;
                    851:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                    852:   if (!v) nrerror("allocation failure in ivector");
                    853:   return v-nl+NR_END;
                    854: }
                    855: 
                    856: /******************free ivector **************************/
                    857: void free_ivector(int *v, long nl, long nh)
                    858: {
                    859:   free((FREE_ARG)(v+nl-NR_END));
                    860: }
                    861: 
                    862: /************************lvector *******************************/
                    863: long *lvector(long nl,long nh)
                    864: {
                    865:   long *v;
                    866:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                    867:   if (!v) nrerror("allocation failure in ivector");
                    868:   return v-nl+NR_END;
                    869: }
                    870: 
                    871: /******************free lvector **************************/
                    872: void free_lvector(long *v, long nl, long nh)
                    873: {
                    874:   free((FREE_ARG)(v+nl-NR_END));
                    875: }
                    876: 
                    877: /******************* imatrix *******************************/
                    878: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                    879:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                    880: { 
                    881:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                    882:   int **m; 
                    883:   
                    884:   /* allocate pointers to rows */ 
                    885:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                    886:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                    887:   m += NR_END; 
                    888:   m -= nrl; 
                    889:   
                    890:   
                    891:   /* allocate rows and set pointers to them */ 
                    892:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                    893:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                    894:   m[nrl] += NR_END; 
                    895:   m[nrl] -= ncl; 
                    896:   
                    897:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                    898:   
                    899:   /* return pointer to array of pointers to rows */ 
                    900:   return m; 
                    901: } 
                    902: 
                    903: /****************** free_imatrix *************************/
                    904: void free_imatrix(m,nrl,nrh,ncl,nch)
                    905:       int **m;
                    906:       long nch,ncl,nrh,nrl; 
                    907:      /* free an int matrix allocated by imatrix() */ 
                    908: { 
                    909:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                    910:   free((FREE_ARG) (m+nrl-NR_END)); 
                    911: } 
                    912: 
                    913: /******************* matrix *******************************/
                    914: double **matrix(long nrl, long nrh, long ncl, long nch)
                    915: {
                    916:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                    917:   double **m;
                    918: 
                    919:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                    920:   if (!m) nrerror("allocation failure 1 in matrix()");
                    921:   m += NR_END;
                    922:   m -= nrl;
                    923: 
                    924:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                    925:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                    926:   m[nrl] += NR_END;
                    927:   m[nrl] -= ncl;
                    928: 
                    929:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                    930:   return m;
1.145     brouard   931:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                    932: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                    933: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard   934:    */
                    935: }
                    936: 
                    937: /*************************free matrix ************************/
                    938: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                    939: {
                    940:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                    941:   free((FREE_ARG)(m+nrl-NR_END));
                    942: }
                    943: 
                    944: /******************* ma3x *******************************/
                    945: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                    946: {
                    947:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                    948:   double ***m;
                    949: 
                    950:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                    951:   if (!m) nrerror("allocation failure 1 in matrix()");
                    952:   m += NR_END;
                    953:   m -= nrl;
                    954: 
                    955:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                    956:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                    957:   m[nrl] += NR_END;
                    958:   m[nrl] -= ncl;
                    959: 
                    960:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                    961: 
                    962:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                    963:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                    964:   m[nrl][ncl] += NR_END;
                    965:   m[nrl][ncl] -= nll;
                    966:   for (j=ncl+1; j<=nch; j++) 
                    967:     m[nrl][j]=m[nrl][j-1]+nlay;
                    968:   
                    969:   for (i=nrl+1; i<=nrh; i++) {
                    970:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                    971:     for (j=ncl+1; j<=nch; j++) 
                    972:       m[i][j]=m[i][j-1]+nlay;
                    973:   }
                    974:   return m; 
                    975:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                    976:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                    977:   */
                    978: }
                    979: 
                    980: /*************************free ma3x ************************/
                    981: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                    982: {
                    983:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                    984:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                    985:   free((FREE_ARG)(m+nrl-NR_END));
                    986: }
                    987: 
                    988: /*************** function subdirf ***********/
                    989: char *subdirf(char fileres[])
                    990: {
                    991:   /* Caution optionfilefiname is hidden */
                    992:   strcpy(tmpout,optionfilefiname);
                    993:   strcat(tmpout,"/"); /* Add to the right */
                    994:   strcat(tmpout,fileres);
                    995:   return tmpout;
                    996: }
                    997: 
                    998: /*************** function subdirf2 ***********/
                    999: char *subdirf2(char fileres[], char *preop)
                   1000: {
                   1001:   
                   1002:   /* Caution optionfilefiname is hidden */
                   1003:   strcpy(tmpout,optionfilefiname);
                   1004:   strcat(tmpout,"/");
                   1005:   strcat(tmpout,preop);
                   1006:   strcat(tmpout,fileres);
                   1007:   return tmpout;
                   1008: }
                   1009: 
                   1010: /*************** function subdirf3 ***********/
                   1011: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1012: {
                   1013:   
                   1014:   /* Caution optionfilefiname is hidden */
                   1015:   strcpy(tmpout,optionfilefiname);
                   1016:   strcat(tmpout,"/");
                   1017:   strcat(tmpout,preop);
                   1018:   strcat(tmpout,preop2);
                   1019:   strcat(tmpout,fileres);
                   1020:   return tmpout;
                   1021: }
                   1022: 
                   1023: /***************** f1dim *************************/
                   1024: extern int ncom; 
                   1025: extern double *pcom,*xicom;
                   1026: extern double (*nrfunc)(double []); 
                   1027:  
                   1028: double f1dim(double x) 
                   1029: { 
                   1030:   int j; 
                   1031:   double f;
                   1032:   double *xt; 
                   1033:  
                   1034:   xt=vector(1,ncom); 
                   1035:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1036:   f=(*nrfunc)(xt); 
                   1037:   free_vector(xt,1,ncom); 
                   1038:   return f; 
                   1039: } 
                   1040: 
                   1041: /*****************brent *************************/
                   1042: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
                   1043: { 
                   1044:   int iter; 
                   1045:   double a,b,d,etemp;
                   1046:   double fu,fv,fw,fx;
                   1047:   double ftemp;
                   1048:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1049:   double e=0.0; 
                   1050:  
                   1051:   a=(ax < cx ? ax : cx); 
                   1052:   b=(ax > cx ? ax : cx); 
                   1053:   x=w=v=bx; 
                   1054:   fw=fv=fx=(*f)(x); 
                   1055:   for (iter=1;iter<=ITMAX;iter++) { 
                   1056:     xm=0.5*(a+b); 
                   1057:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1058:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1059:     printf(".");fflush(stdout);
                   1060:     fprintf(ficlog,".");fflush(ficlog);
                   1061: #ifdef DEBUG
                   1062:     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);
                   1063:     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);
                   1064:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1065: #endif
                   1066:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1067:       *xmin=x; 
                   1068:       return fx; 
                   1069:     } 
                   1070:     ftemp=fu;
                   1071:     if (fabs(e) > tol1) { 
                   1072:       r=(x-w)*(fx-fv); 
                   1073:       q=(x-v)*(fx-fw); 
                   1074:       p=(x-v)*q-(x-w)*r; 
                   1075:       q=2.0*(q-r); 
                   1076:       if (q > 0.0) p = -p; 
                   1077:       q=fabs(q); 
                   1078:       etemp=e; 
                   1079:       e=d; 
                   1080:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1081:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1082:       else { 
                   1083:        d=p/q; 
                   1084:        u=x+d; 
                   1085:        if (u-a < tol2 || b-u < tol2) 
                   1086:          d=SIGN(tol1,xm-x); 
                   1087:       } 
                   1088:     } else { 
                   1089:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1090:     } 
                   1091:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1092:     fu=(*f)(u); 
                   1093:     if (fu <= fx) { 
                   1094:       if (u >= x) a=x; else b=x; 
                   1095:       SHFT(v,w,x,u) 
                   1096:        SHFT(fv,fw,fx,fu) 
                   1097:        } else { 
                   1098:          if (u < x) a=u; else b=u; 
                   1099:          if (fu <= fw || w == x) { 
                   1100:            v=w; 
                   1101:            w=u; 
                   1102:            fv=fw; 
                   1103:            fw=fu; 
                   1104:          } else if (fu <= fv || v == x || v == w) { 
                   1105:            v=u; 
                   1106:            fv=fu; 
                   1107:          } 
                   1108:        } 
                   1109:   } 
                   1110:   nrerror("Too many iterations in brent"); 
                   1111:   *xmin=x; 
                   1112:   return fx; 
                   1113: } 
                   1114: 
                   1115: /****************** mnbrak ***********************/
                   1116: 
                   1117: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1118:            double (*func)(double)) 
                   1119: { 
                   1120:   double ulim,u,r,q, dum;
                   1121:   double fu; 
                   1122:  
                   1123:   *fa=(*func)(*ax); 
                   1124:   *fb=(*func)(*bx); 
                   1125:   if (*fb > *fa) { 
                   1126:     SHFT(dum,*ax,*bx,dum) 
                   1127:       SHFT(dum,*fb,*fa,dum) 
                   1128:       } 
                   1129:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1130:   *fc=(*func)(*cx); 
                   1131:   while (*fb > *fc) { 
                   1132:     r=(*bx-*ax)*(*fb-*fc); 
                   1133:     q=(*bx-*cx)*(*fb-*fa); 
                   1134:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
                   1135:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); 
                   1136:     ulim=(*bx)+GLIMIT*(*cx-*bx); 
                   1137:     if ((*bx-u)*(u-*cx) > 0.0) { 
                   1138:       fu=(*func)(u); 
                   1139:     } else if ((*cx-u)*(u-ulim) > 0.0) { 
                   1140:       fu=(*func)(u); 
                   1141:       if (fu < *fc) { 
                   1142:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   1143:          SHFT(*fb,*fc,fu,(*func)(u)) 
                   1144:          } 
                   1145:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { 
                   1146:       u=ulim; 
                   1147:       fu=(*func)(u); 
                   1148:     } else { 
                   1149:       u=(*cx)+GOLD*(*cx-*bx); 
                   1150:       fu=(*func)(u); 
                   1151:     } 
                   1152:     SHFT(*ax,*bx,*cx,u) 
                   1153:       SHFT(*fa,*fb,*fc,fu) 
                   1154:       } 
                   1155: } 
                   1156: 
                   1157: /*************** linmin ************************/
                   1158: 
                   1159: int ncom; 
                   1160: double *pcom,*xicom;
                   1161: double (*nrfunc)(double []); 
                   1162:  
                   1163: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1164: { 
                   1165:   double brent(double ax, double bx, double cx, 
                   1166:               double (*f)(double), double tol, double *xmin); 
                   1167:   double f1dim(double x); 
                   1168:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1169:              double *fc, double (*func)(double)); 
                   1170:   int j; 
                   1171:   double xx,xmin,bx,ax; 
                   1172:   double fx,fb,fa;
                   1173:  
                   1174:   ncom=n; 
                   1175:   pcom=vector(1,n); 
                   1176:   xicom=vector(1,n); 
                   1177:   nrfunc=func; 
                   1178:   for (j=1;j<=n;j++) { 
                   1179:     pcom[j]=p[j]; 
                   1180:     xicom[j]=xi[j]; 
                   1181:   } 
                   1182:   ax=0.0; 
                   1183:   xx=1.0; 
                   1184:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); 
                   1185:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); 
                   1186: #ifdef DEBUG
                   1187:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1188:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1189: #endif
                   1190:   for (j=1;j<=n;j++) { 
                   1191:     xi[j] *= xmin; 
                   1192:     p[j] += xi[j]; 
                   1193:   } 
                   1194:   free_vector(xicom,1,n); 
                   1195:   free_vector(pcom,1,n); 
                   1196: } 
                   1197: 
                   1198: char *asc_diff_time(long time_sec, char ascdiff[])
                   1199: {
                   1200:   long sec_left, days, hours, minutes;
                   1201:   days = (time_sec) / (60*60*24);
                   1202:   sec_left = (time_sec) % (60*60*24);
                   1203:   hours = (sec_left) / (60*60) ;
                   1204:   sec_left = (sec_left) %(60*60);
                   1205:   minutes = (sec_left) /60;
                   1206:   sec_left = (sec_left) % (60);
1.141     brouard  1207:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
1.126     brouard  1208:   return ascdiff;
                   1209: }
                   1210: 
                   1211: /*************** powell ************************/
                   1212: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1213:            double (*func)(double [])) 
                   1214: { 
                   1215:   void linmin(double p[], double xi[], int n, double *fret, 
                   1216:              double (*func)(double [])); 
                   1217:   int i,ibig,j; 
                   1218:   double del,t,*pt,*ptt,*xit;
                   1219:   double fp,fptt;
                   1220:   double *xits;
                   1221:   int niterf, itmp;
                   1222: 
                   1223:   pt=vector(1,n); 
                   1224:   ptt=vector(1,n); 
                   1225:   xit=vector(1,n); 
                   1226:   xits=vector(1,n); 
                   1227:   *fret=(*func)(p); 
                   1228:   for (j=1;j<=n;j++) pt[j]=p[j]; 
                   1229:   for (*iter=1;;++(*iter)) { 
                   1230:     fp=(*fret); 
                   1231:     ibig=0; 
                   1232:     del=0.0; 
                   1233:     last_time=curr_time;
                   1234:     (void) gettimeofday(&curr_time,&tzp);
                   1235:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec);fflush(stdout);
                   1236:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec); fflush(ficlog);
                   1237: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */
                   1238:    for (i=1;i<=n;i++) {
                   1239:       printf(" %d %.12f",i, p[i]);
                   1240:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1241:       fprintf(ficrespow," %.12lf", p[i]);
                   1242:     }
                   1243:     printf("\n");
                   1244:     fprintf(ficlog,"\n");
                   1245:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1246:     if(*iter <=3){
                   1247:       tm = *localtime(&curr_time.tv_sec);
                   1248:       strcpy(strcurr,asctime(&tm));
                   1249: /*       asctime_r(&tm,strcurr); */
                   1250:       forecast_time=curr_time; 
                   1251:       itmp = strlen(strcurr);
                   1252:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1253:        strcurr[itmp-1]='\0';
                   1254:       printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
                   1255:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
                   1256:       for(niterf=10;niterf<=30;niterf+=10){
                   1257:        forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);
                   1258:        tmf = *localtime(&forecast_time.tv_sec);
                   1259: /*     asctime_r(&tmf,strfor); */
                   1260:        strcpy(strfor,asctime(&tmf));
                   1261:        itmp = strlen(strfor);
                   1262:        if(strfor[itmp-1]=='\n')
                   1263:        strfor[itmp-1]='\0';
                   1264:        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(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);
                   1265:        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(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);
                   1266:       }
                   1267:     }
                   1268:     for (i=1;i<=n;i++) { 
                   1269:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
                   1270:       fptt=(*fret); 
                   1271: #ifdef DEBUG
                   1272:       printf("fret=%lf \n",*fret);
                   1273:       fprintf(ficlog,"fret=%lf \n",*fret);
                   1274: #endif
                   1275:       printf("%d",i);fflush(stdout);
                   1276:       fprintf(ficlog,"%d",i);fflush(ficlog);
                   1277:       linmin(p,xit,n,fret,func); 
                   1278:       if (fabs(fptt-(*fret)) > del) { 
                   1279:        del=fabs(fptt-(*fret)); 
                   1280:        ibig=i; 
                   1281:       } 
                   1282: #ifdef DEBUG
                   1283:       printf("%d %.12e",i,(*fret));
                   1284:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1285:       for (j=1;j<=n;j++) {
                   1286:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1287:        printf(" x(%d)=%.12e",j,xit[j]);
                   1288:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1289:       }
                   1290:       for(j=1;j<=n;j++) {
                   1291:        printf(" p=%.12e",p[j]);
                   1292:        fprintf(ficlog," p=%.12e",p[j]);
                   1293:       }
                   1294:       printf("\n");
                   1295:       fprintf(ficlog,"\n");
                   1296: #endif
                   1297:     } 
                   1298:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
                   1299: #ifdef DEBUG
                   1300:       int k[2],l;
                   1301:       k[0]=1;
                   1302:       k[1]=-1;
                   1303:       printf("Max: %.12e",(*func)(p));
                   1304:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1305:       for (j=1;j<=n;j++) {
                   1306:        printf(" %.12e",p[j]);
                   1307:        fprintf(ficlog," %.12e",p[j]);
                   1308:       }
                   1309:       printf("\n");
                   1310:       fprintf(ficlog,"\n");
                   1311:       for(l=0;l<=1;l++) {
                   1312:        for (j=1;j<=n;j++) {
                   1313:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1314:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1315:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1316:        }
                   1317:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1318:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1319:       }
                   1320: #endif
                   1321: 
                   1322: 
                   1323:       free_vector(xit,1,n); 
                   1324:       free_vector(xits,1,n); 
                   1325:       free_vector(ptt,1,n); 
                   1326:       free_vector(pt,1,n); 
                   1327:       return; 
                   1328:     } 
                   1329:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
                   1330:     for (j=1;j<=n;j++) { 
                   1331:       ptt[j]=2.0*p[j]-pt[j]; 
                   1332:       xit[j]=p[j]-pt[j]; 
                   1333:       pt[j]=p[j]; 
                   1334:     } 
                   1335:     fptt=(*func)(ptt); 
                   1336:     if (fptt < fp) { 
                   1337:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); 
                   1338:       if (t < 0.0) { 
                   1339:        linmin(p,xit,n,fret,func); 
                   1340:        for (j=1;j<=n;j++) { 
                   1341:          xi[j][ibig]=xi[j][n]; 
                   1342:          xi[j][n]=xit[j]; 
                   1343:        }
                   1344: #ifdef DEBUG
                   1345:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1346:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1347:        for(j=1;j<=n;j++){
                   1348:          printf(" %.12e",xit[j]);
                   1349:          fprintf(ficlog," %.12e",xit[j]);
                   1350:        }
                   1351:        printf("\n");
                   1352:        fprintf(ficlog,"\n");
                   1353: #endif
                   1354:       }
                   1355:     } 
                   1356:   } 
                   1357: } 
                   1358: 
                   1359: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1360: 
                   1361: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                   1362: {
                   1363:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                   1364:      matrix by transitions matrix until convergence is reached */
                   1365: 
                   1366:   int i, ii,j,k;
                   1367:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1368:   /* double **matprod2(); */ /* test */
1.131     brouard  1369:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1370:   double **newm;
                   1371:   double agefin, delaymax=50 ; /* Max number of years to converge */
                   1372: 
                   1373:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1374:     for (j=1;j<=nlstate+ndeath;j++){
                   1375:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1376:     }
                   1377: 
                   1378:    cov[1]=1.;
                   1379:  
                   1380:  /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   1381:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   1382:     newm=savm;
                   1383:     /* Covariates have to be included here again */
1.138     brouard  1384:     cov[2]=agefin;
                   1385:     
                   1386:     for (k=1; k<=cptcovn;k++) {
                   1387:       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145     brouard  1388:       /*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]]);*/
1.138     brouard  1389:     }
1.145     brouard  1390:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   1391:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   1392:     /*   cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
1.138     brouard  1393:     
                   1394:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1395:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1396:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  1397:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   1398:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  1399:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  1400:     
1.126     brouard  1401:     savm=oldm;
                   1402:     oldm=newm;
                   1403:     maxmax=0.;
                   1404:     for(j=1;j<=nlstate;j++){
                   1405:       min=1.;
                   1406:       max=0.;
                   1407:       for(i=1; i<=nlstate; i++) {
                   1408:        sumnew=0;
                   1409:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   1410:        prlim[i][j]= newm[i][j]/(1-sumnew);
1.145     brouard  1411:         /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
1.126     brouard  1412:        max=FMAX(max,prlim[i][j]);
                   1413:        min=FMIN(min,prlim[i][j]);
                   1414:       }
                   1415:       maxmin=max-min;
                   1416:       maxmax=FMAX(maxmax,maxmin);
                   1417:     }
                   1418:     if(maxmax < ftolpl){
                   1419:       return prlim;
                   1420:     }
                   1421:   }
                   1422: }
                   1423: 
                   1424: /*************** transition probabilities ***************/ 
                   1425: 
                   1426: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   1427: {
1.138     brouard  1428:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   1429:      computes the probability to be observed in state j being in state i by appying the
                   1430:      model to the ncovmodel covariates (including constant and age).
                   1431:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   1432:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   1433:      ncth covariate in the global vector x is given by the formula:
                   1434:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   1435:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   1436:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   1437:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   1438:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   1439:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   1440:   */
                   1441:   double s1, lnpijopii;
1.126     brouard  1442:   /*double t34;*/
                   1443:   int i,j,j1, nc, ii, jj;
                   1444: 
                   1445:     for(i=1; i<= nlstate; i++){
                   1446:       for(j=1; j<i;j++){
1.138     brouard  1447:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1448:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   1449:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   1450: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1451:        }
1.138     brouard  1452:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   1453: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1454:       }
                   1455:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  1456:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1457:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   1458:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   1459: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  1460:        }
1.138     brouard  1461:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  1462:       }
                   1463:     }
                   1464:     
                   1465:     for(i=1; i<= nlstate; i++){
                   1466:       s1=0;
1.131     brouard  1467:       for(j=1; j<i; j++){
1.138     brouard  1468:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1469:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1470:       }
                   1471:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  1472:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1473:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1474:       }
1.138     brouard  1475:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  1476:       ps[i][i]=1./(s1+1.);
1.138     brouard  1477:       /* Computing other pijs */
1.126     brouard  1478:       for(j=1; j<i; j++)
                   1479:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1480:       for(j=i+1; j<=nlstate+ndeath; j++)
                   1481:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1482:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   1483:     } /* end i */
                   1484:     
                   1485:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   1486:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   1487:        ps[ii][jj]=0;
                   1488:        ps[ii][ii]=1;
                   1489:       }
                   1490:     }
                   1491:     
1.145     brouard  1492:     
                   1493:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   1494:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   1495:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   1496:     /*   } */
                   1497:     /*   printf("\n "); */
                   1498:     /* } */
                   1499:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   1500:     /*
1.126     brouard  1501:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   1502:       goto end;*/
                   1503:     return ps;
                   1504: }
                   1505: 
                   1506: /**************** Product of 2 matrices ******************/
                   1507: 
1.145     brouard  1508: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  1509: {
                   1510:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   1511:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   1512:   /* in, b, out are matrice of pointers which should have been initialized 
                   1513:      before: only the contents of out is modified. The function returns
                   1514:      a pointer to pointers identical to out */
1.145     brouard  1515:   int i, j, k;
1.126     brouard  1516:   for(i=nrl; i<= nrh; i++)
1.145     brouard  1517:     for(k=ncolol; k<=ncoloh; k++){
                   1518:       out[i][k]=0.;
                   1519:       for(j=ncl; j<=nch; j++)
                   1520:        out[i][k] +=in[i][j]*b[j][k];
                   1521:     }
1.126     brouard  1522:   return out;
                   1523: }
                   1524: 
                   1525: 
                   1526: /************* Higher Matrix Product ***************/
                   1527: 
                   1528: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   1529: {
                   1530:   /* Computes the transition matrix starting at age 'age' over 
                   1531:      'nhstepm*hstepm*stepm' months (i.e. until
                   1532:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   1533:      nhstepm*hstepm matrices. 
                   1534:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   1535:      (typically every 2 years instead of every month which is too big 
                   1536:      for the memory).
                   1537:      Model is determined by parameters x and covariates have to be 
                   1538:      included manually here. 
                   1539: 
                   1540:      */
                   1541: 
                   1542:   int i, j, d, h, k;
1.131     brouard  1543:   double **out, cov[NCOVMAX+1];
1.126     brouard  1544:   double **newm;
                   1545: 
                   1546:   /* Hstepm could be zero and should return the unit matrix */
                   1547:   for (i=1;i<=nlstate+ndeath;i++)
                   1548:     for (j=1;j<=nlstate+ndeath;j++){
                   1549:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   1550:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   1551:     }
                   1552:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   1553:   for(h=1; h <=nhstepm; h++){
                   1554:     for(d=1; d <=hstepm; d++){
                   1555:       newm=savm;
                   1556:       /* Covariates have to be included here again */
                   1557:       cov[1]=1.;
                   1558:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131     brouard  1559:       for (k=1; k<=cptcovn;k++) 
                   1560:        cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126     brouard  1561:       for (k=1; k<=cptcovage;k++)
                   1562:        cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145     brouard  1563:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126     brouard  1564:        cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   1565: 
                   1566: 
                   1567:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   1568:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   1569:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   1570:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1571:       savm=oldm;
                   1572:       oldm=newm;
                   1573:     }
                   1574:     for(i=1; i<=nlstate+ndeath; i++)
                   1575:       for(j=1;j<=nlstate+ndeath;j++) {
                   1576:        po[i][j][h]=newm[i][j];
1.128     brouard  1577:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  1578:       }
1.128     brouard  1579:     /*printf("h=%d ",h);*/
1.126     brouard  1580:   } /* end h */
1.128     brouard  1581: /*     printf("\n H=%d \n",h); */
1.126     brouard  1582:   return po;
                   1583: }
                   1584: 
                   1585: 
                   1586: /*************** log-likelihood *************/
                   1587: double func( double *x)
                   1588: {
                   1589:   int i, ii, j, k, mi, d, kk;
1.131     brouard  1590:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  1591:   double **out;
                   1592:   double sw; /* Sum of weights */
                   1593:   double lli; /* Individual log likelihood */
                   1594:   int s1, s2;
                   1595:   double bbh, survp;
                   1596:   long ipmx;
                   1597:   /*extern weight */
                   1598:   /* We are differentiating ll according to initial status */
                   1599:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   1600:   /*for(i=1;i<imx;i++) 
                   1601:     printf(" %d\n",s[4][i]);
                   1602:   */
                   1603:   cov[1]=1.;
                   1604: 
                   1605:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   1606: 
                   1607:   if(mle==1){
                   1608:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  1609:       /* Computes the values of the ncovmodel covariates of the model
                   1610:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   1611:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   1612:         to be observed in j being in i according to the model.
                   1613:        */
1.145     brouard  1614:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
                   1615:        cov[2+k]=covar[Tvar[k]][i];
                   1616:       }
1.137     brouard  1617:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  1618:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  1619:         has been calculated etc */
1.126     brouard  1620:       for(mi=1; mi<= wav[i]-1; mi++){
                   1621:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1622:          for (j=1;j<=nlstate+ndeath;j++){
                   1623:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1624:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1625:          }
                   1626:        for(d=0; d<dh[mi][i]; d++){
                   1627:          newm=savm;
                   1628:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1629:          for (kk=1; kk<=cptcovage;kk++) {
1.137     brouard  1630:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  1631:          }
                   1632:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1633:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1634:          savm=oldm;
                   1635:          oldm=newm;
                   1636:        } /* end mult */
                   1637:       
                   1638:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   1639:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   1640:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   1641:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   1642:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   1643:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   1644:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   1645:         * probability in order to take into account the bias as a fraction of the way
                   1646:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   1647:         * -stepm/2 to stepm/2 .
                   1648:         * For stepm=1 the results are the same as for previous versions of Imach.
                   1649:         * For stepm > 1 the results are less biased than in previous versions. 
                   1650:         */
                   1651:        s1=s[mw[mi][i]][i];
                   1652:        s2=s[mw[mi+1][i]][i];
                   1653:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1654:        /* bias bh is positive if real duration
                   1655:         * is higher than the multiple of stepm and negative otherwise.
                   1656:         */
                   1657:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   1658:        if( s2 > nlstate){ 
                   1659:          /* i.e. if s2 is a death state and if the date of death is known 
                   1660:             then the contribution to the likelihood is the probability to 
                   1661:             die between last step unit time and current  step unit time, 
                   1662:             which is also equal to probability to die before dh 
                   1663:             minus probability to die before dh-stepm . 
                   1664:             In version up to 0.92 likelihood was computed
                   1665:        as if date of death was unknown. Death was treated as any other
                   1666:        health state: the date of the interview describes the actual state
                   1667:        and not the date of a change in health state. The former idea was
                   1668:        to consider that at each interview the state was recorded
                   1669:        (healthy, disable or death) and IMaCh was corrected; but when we
                   1670:        introduced the exact date of death then we should have modified
                   1671:        the contribution of an exact death to the likelihood. This new
                   1672:        contribution is smaller and very dependent of the step unit
                   1673:        stepm. It is no more the probability to die between last interview
                   1674:        and month of death but the probability to survive from last
                   1675:        interview up to one month before death multiplied by the
                   1676:        probability to die within a month. Thanks to Chris
                   1677:        Jackson for correcting this bug.  Former versions increased
                   1678:        mortality artificially. The bad side is that we add another loop
                   1679:        which slows down the processing. The difference can be up to 10%
                   1680:        lower mortality.
                   1681:          */
                   1682:          lli=log(out[s1][s2] - savm[s1][s2]);
                   1683: 
                   1684: 
                   1685:        } else if  (s2==-2) {
                   1686:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   1687:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1688:          /*survp += out[s1][j]; */
                   1689:          lli= log(survp);
                   1690:        }
                   1691:        
                   1692:        else if  (s2==-4) { 
                   1693:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   1694:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1695:          lli= log(survp); 
                   1696:        } 
                   1697: 
                   1698:        else if  (s2==-5) { 
                   1699:          for (j=1,survp=0. ; j<=2; j++)  
                   1700:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1701:          lli= log(survp); 
                   1702:        } 
                   1703:        
                   1704:        else{
                   1705:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   1706:          /*  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 */
                   1707:        } 
                   1708:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   1709:        /*if(lli ==000.0)*/
                   1710:        /*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); */
                   1711:        ipmx +=1;
                   1712:        sw += weight[i];
                   1713:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1714:       } /* end of wave */
                   1715:     } /* end of individual */
                   1716:   }  else if(mle==2){
                   1717:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1718:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1719:       for(mi=1; mi<= wav[i]-1; mi++){
                   1720:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1721:          for (j=1;j<=nlstate+ndeath;j++){
                   1722:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1723:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1724:          }
                   1725:        for(d=0; d<=dh[mi][i]; d++){
                   1726:          newm=savm;
                   1727:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1728:          for (kk=1; kk<=cptcovage;kk++) {
                   1729:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1730:          }
                   1731:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1732:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1733:          savm=oldm;
                   1734:          oldm=newm;
                   1735:        } /* end mult */
                   1736:       
                   1737:        s1=s[mw[mi][i]][i];
                   1738:        s2=s[mw[mi+1][i]][i];
                   1739:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1740:        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 */
                   1741:        ipmx +=1;
                   1742:        sw += weight[i];
                   1743:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1744:       } /* end of wave */
                   1745:     } /* end of individual */
                   1746:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   1747:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1748:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1749:       for(mi=1; mi<= wav[i]-1; mi++){
                   1750:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1751:          for (j=1;j<=nlstate+ndeath;j++){
                   1752:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1753:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1754:          }
                   1755:        for(d=0; d<dh[mi][i]; d++){
                   1756:          newm=savm;
                   1757:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1758:          for (kk=1; kk<=cptcovage;kk++) {
                   1759:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1760:          }
                   1761:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1762:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1763:          savm=oldm;
                   1764:          oldm=newm;
                   1765:        } /* end mult */
                   1766:       
                   1767:        s1=s[mw[mi][i]][i];
                   1768:        s2=s[mw[mi+1][i]][i];
                   1769:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1770:        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 */
                   1771:        ipmx +=1;
                   1772:        sw += weight[i];
                   1773:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1774:       } /* end of wave */
                   1775:     } /* end of individual */
                   1776:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   1777:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1778:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1779:       for(mi=1; mi<= wav[i]-1; mi++){
                   1780:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1781:          for (j=1;j<=nlstate+ndeath;j++){
                   1782:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1783:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1784:          }
                   1785:        for(d=0; d<dh[mi][i]; d++){
                   1786:          newm=savm;
                   1787:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1788:          for (kk=1; kk<=cptcovage;kk++) {
                   1789:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1790:          }
                   1791:        
                   1792:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1793:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1794:          savm=oldm;
                   1795:          oldm=newm;
                   1796:        } /* end mult */
                   1797:       
                   1798:        s1=s[mw[mi][i]][i];
                   1799:        s2=s[mw[mi+1][i]][i];
                   1800:        if( s2 > nlstate){ 
                   1801:          lli=log(out[s1][s2] - savm[s1][s2]);
                   1802:        }else{
                   1803:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   1804:        }
                   1805:        ipmx +=1;
                   1806:        sw += weight[i];
                   1807:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1808: /*     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]); */
                   1809:       } /* end of wave */
                   1810:     } /* end of individual */
                   1811:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   1812:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1813:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1814:       for(mi=1; mi<= wav[i]-1; mi++){
                   1815:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1816:          for (j=1;j<=nlstate+ndeath;j++){
                   1817:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1818:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1819:          }
                   1820:        for(d=0; d<dh[mi][i]; d++){
                   1821:          newm=savm;
                   1822:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1823:          for (kk=1; kk<=cptcovage;kk++) {
                   1824:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1825:          }
                   1826:        
                   1827:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1828:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1829:          savm=oldm;
                   1830:          oldm=newm;
                   1831:        } /* end mult */
                   1832:       
                   1833:        s1=s[mw[mi][i]][i];
                   1834:        s2=s[mw[mi+1][i]][i];
                   1835:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   1836:        ipmx +=1;
                   1837:        sw += weight[i];
                   1838:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1839:        /*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]);*/
                   1840:       } /* end of wave */
                   1841:     } /* end of individual */
                   1842:   } /* End of if */
                   1843:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   1844:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   1845:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   1846:   return -l;
                   1847: }
                   1848: 
                   1849: /*************** log-likelihood *************/
                   1850: double funcone( double *x)
                   1851: {
                   1852:   /* Same as likeli but slower because of a lot of printf and if */
                   1853:   int i, ii, j, k, mi, d, kk;
1.131     brouard  1854:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  1855:   double **out;
                   1856:   double lli; /* Individual log likelihood */
                   1857:   double llt;
                   1858:   int s1, s2;
                   1859:   double bbh, survp;
                   1860:   /*extern weight */
                   1861:   /* We are differentiating ll according to initial status */
                   1862:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   1863:   /*for(i=1;i<imx;i++) 
                   1864:     printf(" %d\n",s[4][i]);
                   1865:   */
                   1866:   cov[1]=1.;
                   1867: 
                   1868:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   1869: 
                   1870:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1871:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1872:     for(mi=1; mi<= wav[i]-1; mi++){
                   1873:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   1874:        for (j=1;j<=nlstate+ndeath;j++){
                   1875:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1876:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1877:        }
                   1878:       for(d=0; d<dh[mi][i]; d++){
                   1879:        newm=savm;
                   1880:        cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1881:        for (kk=1; kk<=cptcovage;kk++) {
                   1882:          cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1883:        }
1.145     brouard  1884:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  1885:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1886:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  1887:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   1888:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  1889:        savm=oldm;
                   1890:        oldm=newm;
                   1891:       } /* end mult */
                   1892:       
                   1893:       s1=s[mw[mi][i]][i];
                   1894:       s2=s[mw[mi+1][i]][i];
                   1895:       bbh=(double)bh[mi][i]/(double)stepm; 
                   1896:       /* bias is positive if real duration
                   1897:        * is higher than the multiple of stepm and negative otherwise.
                   1898:        */
                   1899:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   1900:        lli=log(out[s1][s2] - savm[s1][s2]);
                   1901:       } else if  (s2==-2) {
                   1902:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   1903:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1904:        lli= log(survp);
                   1905:       }else if (mle==1){
                   1906:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   1907:       } else if(mle==2){
                   1908:        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 */
                   1909:       } else if(mle==3){  /* exponential inter-extrapolation */
                   1910:        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 */
                   1911:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   1912:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  1913:       } else{  /* mle=0 back to 1 */
                   1914:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   1915:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  1916:       } /* End of if */
                   1917:       ipmx +=1;
                   1918:       sw += weight[i];
                   1919:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  1920:       /*printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
1.126     brouard  1921:       if(globpr){
1.141     brouard  1922:        fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126     brouard  1923:  %11.6f %11.6f %11.6f ", \
                   1924:                num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
                   1925:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   1926:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   1927:          llt +=ll[k]*gipmx/gsw;
                   1928:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   1929:        }
                   1930:        fprintf(ficresilk," %10.6f\n", -llt);
                   1931:       }
                   1932:     } /* end of wave */
                   1933:   } /* end of individual */
                   1934:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   1935:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   1936:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   1937:   if(globpr==0){ /* First time we count the contributions and weights */
                   1938:     gipmx=ipmx;
                   1939:     gsw=sw;
                   1940:   }
                   1941:   return -l;
                   1942: }
                   1943: 
                   1944: 
                   1945: /*************** function likelione ***********/
                   1946: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   1947: {
                   1948:   /* This routine should help understanding what is done with 
                   1949:      the selection of individuals/waves and
                   1950:      to check the exact contribution to the likelihood.
                   1951:      Plotting could be done.
                   1952:    */
                   1953:   int k;
                   1954: 
                   1955:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   1956:     strcpy(fileresilk,"ilk"); 
                   1957:     strcat(fileresilk,fileres);
                   1958:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   1959:       printf("Problem with resultfile: %s\n", fileresilk);
                   1960:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   1961:     }
                   1962:     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");
                   1963:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
                   1964:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   1965:     for(k=1; k<=nlstate; k++) 
                   1966:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   1967:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   1968:   }
                   1969: 
                   1970:   *fretone=(*funcone)(p);
                   1971:   if(*globpri !=0){
                   1972:     fclose(ficresilk);
                   1973:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
                   1974:     fflush(fichtm); 
                   1975:   } 
                   1976:   return;
                   1977: }
                   1978: 
                   1979: 
                   1980: /*********** Maximum Likelihood Estimation ***************/
                   1981: 
                   1982: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   1983: {
                   1984:   int i,j, iter;
                   1985:   double **xi;
                   1986:   double fret;
                   1987:   double fretone; /* Only one call to likelihood */
                   1988:   /*  char filerespow[FILENAMELENGTH];*/
                   1989:   xi=matrix(1,npar,1,npar);
                   1990:   for (i=1;i<=npar;i++)
                   1991:     for (j=1;j<=npar;j++)
                   1992:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   1993:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   1994:   strcpy(filerespow,"pow"); 
                   1995:   strcat(filerespow,fileres);
                   1996:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   1997:     printf("Problem with resultfile: %s\n", filerespow);
                   1998:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   1999:   }
                   2000:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2001:   for (i=1;i<=nlstate;i++)
                   2002:     for(j=1;j<=nlstate+ndeath;j++)
                   2003:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2004:   fprintf(ficrespow,"\n");
                   2005: 
                   2006:   powell(p,xi,npar,ftol,&iter,&fret,func);
                   2007: 
                   2008:   free_matrix(xi,1,npar,1,npar);
                   2009:   fclose(ficrespow);
                   2010:   printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
                   2011:   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
                   2012:   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
                   2013: 
                   2014: }
                   2015: 
                   2016: /**** Computes Hessian and covariance matrix ***/
                   2017: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   2018: {
                   2019:   double  **a,**y,*x,pd;
                   2020:   double **hess;
                   2021:   int i, j,jk;
                   2022:   int *indx;
                   2023: 
                   2024:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   2025:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
                   2026:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2027:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2028:   double gompertz(double p[]);
                   2029:   hess=matrix(1,npar,1,npar);
                   2030: 
                   2031:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2032:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2033:   for (i=1;i<=npar;i++){
                   2034:     printf("%d",i);fflush(stdout);
                   2035:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   2036:    
                   2037:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2038:     
                   2039:     /*  printf(" %f ",p[i]);
                   2040:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2041:   }
                   2042:   
                   2043:   for (i=1;i<=npar;i++) {
                   2044:     for (j=1;j<=npar;j++)  {
                   2045:       if (j>i) { 
                   2046:        printf(".%d%d",i,j);fflush(stdout);
                   2047:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   2048:        hess[i][j]=hessij(p,delti,i,j,func,npar);
                   2049:        
                   2050:        hess[j][i]=hess[i][j];    
                   2051:        /*printf(" %lf ",hess[i][j]);*/
                   2052:       }
                   2053:     }
                   2054:   }
                   2055:   printf("\n");
                   2056:   fprintf(ficlog,"\n");
                   2057: 
                   2058:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2059:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2060:   
                   2061:   a=matrix(1,npar,1,npar);
                   2062:   y=matrix(1,npar,1,npar);
                   2063:   x=vector(1,npar);
                   2064:   indx=ivector(1,npar);
                   2065:   for (i=1;i<=npar;i++)
                   2066:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2067:   ludcmp(a,npar,indx,&pd);
                   2068: 
                   2069:   for (j=1;j<=npar;j++) {
                   2070:     for (i=1;i<=npar;i++) x[i]=0;
                   2071:     x[j]=1;
                   2072:     lubksb(a,npar,indx,x);
                   2073:     for (i=1;i<=npar;i++){ 
                   2074:       matcov[i][j]=x[i];
                   2075:     }
                   2076:   }
                   2077: 
                   2078:   printf("\n#Hessian matrix#\n");
                   2079:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2080:   for (i=1;i<=npar;i++) { 
                   2081:     for (j=1;j<=npar;j++) { 
                   2082:       printf("%.3e ",hess[i][j]);
                   2083:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   2084:     }
                   2085:     printf("\n");
                   2086:     fprintf(ficlog,"\n");
                   2087:   }
                   2088: 
                   2089:   /* Recompute Inverse */
                   2090:   for (i=1;i<=npar;i++)
                   2091:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   2092:   ludcmp(a,npar,indx,&pd);
                   2093: 
                   2094:   /*  printf("\n#Hessian matrix recomputed#\n");
                   2095: 
                   2096:   for (j=1;j<=npar;j++) {
                   2097:     for (i=1;i<=npar;i++) x[i]=0;
                   2098:     x[j]=1;
                   2099:     lubksb(a,npar,indx,x);
                   2100:     for (i=1;i<=npar;i++){ 
                   2101:       y[i][j]=x[i];
                   2102:       printf("%.3e ",y[i][j]);
                   2103:       fprintf(ficlog,"%.3e ",y[i][j]);
                   2104:     }
                   2105:     printf("\n");
                   2106:     fprintf(ficlog,"\n");
                   2107:   }
                   2108:   */
                   2109: 
                   2110:   free_matrix(a,1,npar,1,npar);
                   2111:   free_matrix(y,1,npar,1,npar);
                   2112:   free_vector(x,1,npar);
                   2113:   free_ivector(indx,1,npar);
                   2114:   free_matrix(hess,1,npar,1,npar);
                   2115: 
                   2116: 
                   2117: }
                   2118: 
                   2119: /*************** hessian matrix ****************/
                   2120: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   2121: {
                   2122:   int i;
                   2123:   int l=1, lmax=20;
                   2124:   double k1,k2;
1.132     brouard  2125:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2126:   double res;
                   2127:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2128:   double fx;
                   2129:   int k=0,kmax=10;
                   2130:   double l1;
                   2131: 
                   2132:   fx=func(x);
                   2133:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2134:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2135:     l1=pow(10,l);
                   2136:     delts=delt;
                   2137:     for(k=1 ; k <kmax; k=k+1){
                   2138:       delt = delta*(l1*k);
                   2139:       p2[theta]=x[theta] +delt;
1.145     brouard  2140:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2141:       p2[theta]=x[theta]-delt;
                   2142:       k2=func(p2)-fx;
                   2143:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   2144:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   2145:       
1.132     brouard  2146: #ifdef DEBUGHESS
1.126     brouard  2147:       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);
                   2148:       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);
                   2149: #endif
                   2150:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2151:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2152:        k=kmax;
                   2153:       }
                   2154:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
                   2155:        k=kmax; l=lmax*10.;
                   2156:       }
                   2157:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2158:        delts=delt;
                   2159:       }
                   2160:     }
                   2161:   }
                   2162:   delti[theta]=delts;
                   2163:   return res; 
                   2164:   
                   2165: }
                   2166: 
                   2167: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   2168: {
                   2169:   int i;
                   2170:   int l=1, l1, lmax=20;
                   2171:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2172:   double p2[MAXPARM+1];
1.126     brouard  2173:   int k;
                   2174: 
                   2175:   fx=func(x);
                   2176:   for (k=1; k<=2; k++) {
                   2177:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   2178:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2179:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2180:     k1=func(p2)-fx;
                   2181:   
                   2182:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2183:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2184:     k2=func(p2)-fx;
                   2185:   
                   2186:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2187:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2188:     k3=func(p2)-fx;
                   2189:   
                   2190:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2191:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2192:     k4=func(p2)-fx;
                   2193:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   2194: #ifdef DEBUG
                   2195:     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);
                   2196:     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);
                   2197: #endif
                   2198:   }
                   2199:   return res;
                   2200: }
                   2201: 
                   2202: /************** Inverse of matrix **************/
                   2203: void ludcmp(double **a, int n, int *indx, double *d) 
                   2204: { 
                   2205:   int i,imax,j,k; 
                   2206:   double big,dum,sum,temp; 
                   2207:   double *vv; 
                   2208:  
                   2209:   vv=vector(1,n); 
                   2210:   *d=1.0; 
                   2211:   for (i=1;i<=n;i++) { 
                   2212:     big=0.0; 
                   2213:     for (j=1;j<=n;j++) 
                   2214:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   2215:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   2216:     vv[i]=1.0/big; 
                   2217:   } 
                   2218:   for (j=1;j<=n;j++) { 
                   2219:     for (i=1;i<j;i++) { 
                   2220:       sum=a[i][j]; 
                   2221:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   2222:       a[i][j]=sum; 
                   2223:     } 
                   2224:     big=0.0; 
                   2225:     for (i=j;i<=n;i++) { 
                   2226:       sum=a[i][j]; 
                   2227:       for (k=1;k<j;k++) 
                   2228:        sum -= a[i][k]*a[k][j]; 
                   2229:       a[i][j]=sum; 
                   2230:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   2231:        big=dum; 
                   2232:        imax=i; 
                   2233:       } 
                   2234:     } 
                   2235:     if (j != imax) { 
                   2236:       for (k=1;k<=n;k++) { 
                   2237:        dum=a[imax][k]; 
                   2238:        a[imax][k]=a[j][k]; 
                   2239:        a[j][k]=dum; 
                   2240:       } 
                   2241:       *d = -(*d); 
                   2242:       vv[imax]=vv[j]; 
                   2243:     } 
                   2244:     indx[j]=imax; 
                   2245:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   2246:     if (j != n) { 
                   2247:       dum=1.0/(a[j][j]); 
                   2248:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   2249:     } 
                   2250:   } 
                   2251:   free_vector(vv,1,n);  /* Doesn't work */
                   2252: ;
                   2253: } 
                   2254: 
                   2255: void lubksb(double **a, int n, int *indx, double b[]) 
                   2256: { 
                   2257:   int i,ii=0,ip,j; 
                   2258:   double sum; 
                   2259:  
                   2260:   for (i=1;i<=n;i++) { 
                   2261:     ip=indx[i]; 
                   2262:     sum=b[ip]; 
                   2263:     b[ip]=b[i]; 
                   2264:     if (ii) 
                   2265:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   2266:     else if (sum) ii=i; 
                   2267:     b[i]=sum; 
                   2268:   } 
                   2269:   for (i=n;i>=1;i--) { 
                   2270:     sum=b[i]; 
                   2271:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   2272:     b[i]=sum/a[i][i]; 
                   2273:   } 
                   2274: } 
                   2275: 
                   2276: void pstamp(FILE *fichier)
                   2277: {
                   2278:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
                   2279: }
                   2280: 
                   2281: /************ Frequencies ********************/
                   2282: 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[])
                   2283: {  /* Some frequencies */
                   2284:   
1.130     brouard  2285:   int i, m, jk, k1,i1, j1, bool, z1,j;
1.126     brouard  2286:   int first;
                   2287:   double ***freq; /* Frequencies */
                   2288:   double *pp, **prop;
                   2289:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   2290:   char fileresp[FILENAMELENGTH];
                   2291:   
                   2292:   pp=vector(1,nlstate);
                   2293:   prop=matrix(1,nlstate,iagemin,iagemax+3);
                   2294:   strcpy(fileresp,"p");
                   2295:   strcat(fileresp,fileres);
                   2296:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   2297:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   2298:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   2299:     exit(0);
                   2300:   }
                   2301:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   2302:   j1=0;
                   2303:   
                   2304:   j=cptcoveff;
                   2305:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2306: 
                   2307:   first=1;
                   2308: 
1.145     brouard  2309:   /* for(k1=1; k1<=j ; k1++){   /* Loop on covariates */
                   2310:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
                   2311:   /*    j1++;
                   2312: */
                   2313:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  2314:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   2315:        scanf("%d", i);*/
                   2316:       for (i=-5; i<=nlstate+ndeath; i++)  
                   2317:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   2318:          for(m=iagemin; m <= iagemax+3; m++)
                   2319:            freq[i][jk][m]=0;
1.143     brouard  2320:       
                   2321:       for (i=1; i<=nlstate; i++)  
                   2322:        for(m=iagemin; m <= iagemax+3; m++)
                   2323:          prop[i][m]=0;
1.126     brouard  2324:       
                   2325:       dateintsum=0;
                   2326:       k2cpt=0;
                   2327:       for (i=1; i<=imx; i++) {
                   2328:        bool=1;
1.144     brouard  2329:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   2330:          for (z1=1; z1<=cptcoveff; z1++)       
                   2331:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145     brouard  2332:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  2333:               bool=0;
1.145     brouard  2334:               /* 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", 
                   2335:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
                   2336:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144     brouard  2337:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
                   2338:             } 
1.126     brouard  2339:        }
1.144     brouard  2340:  
1.126     brouard  2341:        if (bool==1){
                   2342:          for(m=firstpass; m<=lastpass; m++){
                   2343:            k2=anint[m][i]+(mint[m][i]/12.);
                   2344:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   2345:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2346:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2347:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2348:              if (m<lastpass) {
                   2349:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   2350:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   2351:              }
                   2352:              
                   2353:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   2354:                dateintsum=dateintsum+k2;
                   2355:                k2cpt++;
                   2356:              }
                   2357:              /*}*/
                   2358:          }
                   2359:        }
1.145     brouard  2360:       } /* end i */
1.126     brouard  2361:        
                   2362:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   2363:       pstamp(ficresp);
                   2364:       if  (cptcovn>0) {
                   2365:        fprintf(ficresp, "\n#********** Variable "); 
                   2366:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2367:        fprintf(ficresp, "**********\n#");
1.143     brouard  2368:        fprintf(ficlog, "\n#********** Variable "); 
                   2369:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2370:        fprintf(ficlog, "**********\n#");
1.126     brouard  2371:       }
                   2372:       for(i=1; i<=nlstate;i++) 
                   2373:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   2374:       fprintf(ficresp, "\n");
                   2375:       
                   2376:       for(i=iagemin; i <= iagemax+3; i++){
                   2377:        if(i==iagemax+3){
                   2378:          fprintf(ficlog,"Total");
                   2379:        }else{
                   2380:          if(first==1){
                   2381:            first=0;
                   2382:            printf("See log file for details...\n");
                   2383:          }
                   2384:          fprintf(ficlog,"Age %d", i);
                   2385:        }
                   2386:        for(jk=1; jk <=nlstate ; jk++){
                   2387:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   2388:            pp[jk] += freq[jk][m][i]; 
                   2389:        }
                   2390:        for(jk=1; jk <=nlstate ; jk++){
                   2391:          for(m=-1, pos=0; m <=0 ; m++)
                   2392:            pos += freq[jk][m][i];
                   2393:          if(pp[jk]>=1.e-10){
                   2394:            if(first==1){
1.132     brouard  2395:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  2396:            }
                   2397:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   2398:          }else{
                   2399:            if(first==1)
                   2400:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2401:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2402:          }
                   2403:        }
                   2404: 
                   2405:        for(jk=1; jk <=nlstate ; jk++){
                   2406:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   2407:            pp[jk] += freq[jk][m][i];
                   2408:        }       
                   2409:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   2410:          pos += pp[jk];
                   2411:          posprop += prop[jk][i];
                   2412:        }
                   2413:        for(jk=1; jk <=nlstate ; jk++){
                   2414:          if(pos>=1.e-5){
                   2415:            if(first==1)
                   2416:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2417:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2418:          }else{
                   2419:            if(first==1)
                   2420:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2421:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2422:          }
                   2423:          if( i <= iagemax){
                   2424:            if(pos>=1.e-5){
                   2425:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   2426:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   2427:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   2428:            }
                   2429:            else
                   2430:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   2431:          }
                   2432:        }
                   2433:        
                   2434:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   2435:          for(m=-1; m <=nlstate+ndeath; m++)
                   2436:            if(freq[jk][m][i] !=0 ) {
                   2437:            if(first==1)
                   2438:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2439:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2440:            }
                   2441:        if(i <= iagemax)
                   2442:          fprintf(ficresp,"\n");
                   2443:        if(first==1)
                   2444:          printf("Others in log...\n");
                   2445:        fprintf(ficlog,"\n");
                   2446:       }
1.145     brouard  2447:       /*}*/
1.126     brouard  2448:   }
                   2449:   dateintmean=dateintsum/k2cpt; 
                   2450:  
                   2451:   fclose(ficresp);
                   2452:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   2453:   free_vector(pp,1,nlstate);
                   2454:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   2455:   /* End of Freq */
                   2456: }
                   2457: 
                   2458: /************ Prevalence ********************/
                   2459: 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)
                   2460: {  
                   2461:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   2462:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   2463:      We still use firstpass and lastpass as another selection.
                   2464:   */
                   2465:  
1.130     brouard  2466:   int i, m, jk, k1, i1, j1, bool, z1,j;
1.126     brouard  2467:   double ***freq; /* Frequencies */
                   2468:   double *pp, **prop;
                   2469:   double pos,posprop; 
                   2470:   double  y2; /* in fractional years */
                   2471:   int iagemin, iagemax;
1.145     brouard  2472:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  2473: 
                   2474:   iagemin= (int) agemin;
                   2475:   iagemax= (int) agemax;
                   2476:   /*pp=vector(1,nlstate);*/
                   2477:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   2478:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   2479:   j1=0;
                   2480:   
1.145     brouard  2481:   /*j=cptcoveff;*/
1.126     brouard  2482:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2483:   
1.145     brouard  2484:   first=1;
                   2485:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   2486:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   2487:       j1++;*/
1.126     brouard  2488:       
                   2489:       for (i=1; i<=nlstate; i++)  
                   2490:        for(m=iagemin; m <= iagemax+3; m++)
                   2491:          prop[i][m]=0.0;
                   2492:      
                   2493:       for (i=1; i<=imx; i++) { /* Each individual */
                   2494:        bool=1;
                   2495:        if  (cptcovn>0) {
                   2496:          for (z1=1; z1<=cptcoveff; z1++) 
                   2497:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   2498:              bool=0;
                   2499:        } 
                   2500:        if (bool==1) { 
                   2501:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   2502:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   2503:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   2504:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2505:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2506:              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); 
                   2507:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   2508:                /*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]]);*/
                   2509:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2510:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   2511:              } 
                   2512:            }
                   2513:          } /* end selection of waves */
                   2514:        }
                   2515:       }
                   2516:       for(i=iagemin; i <= iagemax+3; i++){  
                   2517:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   2518:          posprop += prop[jk][i]; 
                   2519:        } 
1.145     brouard  2520:        
1.126     brouard  2521:        for(jk=1; jk <=nlstate ; jk++){     
                   2522:          if( i <=  iagemax){ 
                   2523:            if(posprop>=1.e-5){ 
                   2524:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  2525:            } else{
                   2526:              if(first==1){
                   2527:                first=0;
                   2528:                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]);
                   2529:              }
                   2530:            }
1.126     brouard  2531:          } 
                   2532:        }/* end jk */ 
                   2533:       }/* end i */ 
1.145     brouard  2534:     /*} *//* end i1 */
                   2535:   } /* end j1 */
1.126     brouard  2536:   
                   2537:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   2538:   /*free_vector(pp,1,nlstate);*/
                   2539:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   2540: }  /* End of prevalence */
                   2541: 
                   2542: /************* Waves Concatenation ***************/
                   2543: 
                   2544: 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)
                   2545: {
                   2546:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   2547:      Death is a valid wave (if date is known).
                   2548:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   2549:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   2550:      and mw[mi+1][i]. dh depends on stepm.
                   2551:      */
                   2552: 
                   2553:   int i, mi, m;
                   2554:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   2555:      double sum=0., jmean=0.;*/
                   2556:   int first;
                   2557:   int j, k=0,jk, ju, jl;
                   2558:   double sum=0.;
                   2559:   first=0;
                   2560:   jmin=1e+5;
                   2561:   jmax=-1;
                   2562:   jmean=0.;
                   2563:   for(i=1; i<=imx; i++){
                   2564:     mi=0;
                   2565:     m=firstpass;
                   2566:     while(s[m][i] <= nlstate){
                   2567:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   2568:        mw[++mi][i]=m;
                   2569:       if(m >=lastpass)
                   2570:        break;
                   2571:       else
                   2572:        m++;
                   2573:     }/* end while */
                   2574:     if (s[m][i] > nlstate){
                   2575:       mi++;    /* Death is another wave */
                   2576:       /* if(mi==0)  never been interviewed correctly before death */
                   2577:         /* Only death is a correct wave */
                   2578:       mw[mi][i]=m;
                   2579:     }
                   2580: 
                   2581:     wav[i]=mi;
                   2582:     if(mi==0){
                   2583:       nbwarn++;
                   2584:       if(first==0){
                   2585:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   2586:        first=1;
                   2587:       }
                   2588:       if(first==1){
                   2589:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   2590:       }
                   2591:     } /* end mi==0 */
                   2592:   } /* End individuals */
                   2593: 
                   2594:   for(i=1; i<=imx; i++){
                   2595:     for(mi=1; mi<wav[i];mi++){
                   2596:       if (stepm <=0)
                   2597:        dh[mi][i]=1;
                   2598:       else{
                   2599:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   2600:          if (agedc[i] < 2*AGESUP) {
                   2601:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   2602:            if(j==0) j=1;  /* Survives at least one month after exam */
                   2603:            else if(j<0){
                   2604:              nberr++;
                   2605:              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]);
                   2606:              j=1; /* Temporary Dangerous patch */
                   2607:              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);
                   2608:              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]);
                   2609:              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);
                   2610:            }
                   2611:            k=k+1;
                   2612:            if (j >= jmax){
                   2613:              jmax=j;
                   2614:              ijmax=i;
                   2615:            }
                   2616:            if (j <= jmin){
                   2617:              jmin=j;
                   2618:              ijmin=i;
                   2619:            }
                   2620:            sum=sum+j;
                   2621:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   2622:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   2623:          }
                   2624:        }
                   2625:        else{
                   2626:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   2627: /*       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]); */
                   2628: 
                   2629:          k=k+1;
                   2630:          if (j >= jmax) {
                   2631:            jmax=j;
                   2632:            ijmax=i;
                   2633:          }
                   2634:          else if (j <= jmin){
                   2635:            jmin=j;
                   2636:            ijmin=i;
                   2637:          }
                   2638:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   2639:          /*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]);*/
                   2640:          if(j<0){
                   2641:            nberr++;
                   2642:            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]);
                   2643:            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]);
                   2644:          }
                   2645:          sum=sum+j;
                   2646:        }
                   2647:        jk= j/stepm;
                   2648:        jl= j -jk*stepm;
                   2649:        ju= j -(jk+1)*stepm;
                   2650:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   2651:          if(jl==0){
                   2652:            dh[mi][i]=jk;
                   2653:            bh[mi][i]=0;
                   2654:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  2655:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  2656:            dh[mi][i]=jk+1;
                   2657:            bh[mi][i]=ju;
                   2658:          }
                   2659:        }else{
                   2660:          if(jl <= -ju){
                   2661:            dh[mi][i]=jk;
                   2662:            bh[mi][i]=jl;       /* bias is positive if real duration
                   2663:                                 * is higher than the multiple of stepm and negative otherwise.
                   2664:                                 */
                   2665:          }
                   2666:          else{
                   2667:            dh[mi][i]=jk+1;
                   2668:            bh[mi][i]=ju;
                   2669:          }
                   2670:          if(dh[mi][i]==0){
                   2671:            dh[mi][i]=1; /* At least one step */
                   2672:            bh[mi][i]=ju; /* At least one step */
                   2673:            /*  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);*/
                   2674:          }
                   2675:        } /* end if mle */
                   2676:       }
                   2677:     } /* end wave */
                   2678:   }
                   2679:   jmean=sum/k;
                   2680:   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);
1.141     brouard  2681:   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);
1.126     brouard  2682:  }
                   2683: 
                   2684: /*********** Tricode ****************************/
1.145     brouard  2685: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  2686: {
1.144     brouard  2687:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   2688:   /*     Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   2689:   /* Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  2690:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
                   2691:   /* nbcode[Tvar[j]][1]= 
1.144     brouard  2692:   */
1.130     brouard  2693: 
1.145     brouard  2694:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  2695:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  2696:   int cptcode=0; /* Modality max of covariates j */
                   2697:   int modmincovj=0; /* Modality min of covariates j */
                   2698: 
                   2699: 
1.126     brouard  2700:   cptcoveff=0; 
                   2701:  
1.145     brouard  2702:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144     brouard  2703:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  2704: 
1.145     brouard  2705:   /* Loop on covariates without age and products */
                   2706:   for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
                   2707:     for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the 
1.136     brouard  2708:                               modality of this covariate Vj*/ 
1.145     brouard  2709:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   2710:                                    * If product of Vn*Vm, still boolean *:
                   2711:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   2712:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   2713:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  2714:                                      modality of the nth covariate of individual i. */
1.145     brouard  2715:       if (ij > modmaxcovj)
                   2716:         modmaxcovj=ij; 
                   2717:       else if (ij < modmincovj) 
                   2718:        modmincovj=ij; 
                   2719:       if ((ij < -1) && (ij > NCOVMAX)){
                   2720:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   2721:        exit(1);
                   2722:       }else
1.136     brouard  2723:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  2724:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  2725:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  2726:       /* getting the maximum value of the modality of the covariate
                   2727:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   2728:         female is 1, then modmaxcovj=1.*/
1.126     brouard  2729:     }
1.145     brouard  2730:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
                   2731:     cptcode=modmaxcovj;
1.137     brouard  2732:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  2733:    /*for (i=0; i<=cptcode; i++) {*/
                   2734:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
                   2735:       printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
                   2736:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
                   2737:        ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
                   2738:       }
                   2739:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   2740:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  2741:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  2742: 
1.136     brouard  2743:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145     brouard  2744:     /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
                   2745:     /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
                   2746:        modmincovj=3; modmaxcovj = 7;
                   2747:        There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
                   2748:        which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy 
                   2749:        variables V1_1 and V1_2.
                   2750:        nbcode[Tvar[j]][ij]=k;
                   2751:        nbcode[Tvar[j]][1]=0;
                   2752:        nbcode[Tvar[j]][2]=1;
                   2753:        nbcode[Tvar[j]][3]=2;
                   2754:     */
                   2755:     ij=1; /* ij is similar to i but can jumps over null modalities */
                   2756:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
                   2757:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
                   2758:        /*recode from 0 */
1.131     brouard  2759:        if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
                   2760:          nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
                   2761:                                     k is a modality. If we have model=V1+V1*sex 
                   2762:                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126     brouard  2763:          ij++;
                   2764:        }
                   2765:        if (ij > ncodemax[j]) break; 
1.137     brouard  2766:       }  /* end of loop on */
                   2767:     } /* end of loop on modality */ 
                   2768:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   2769:   
1.145     brouard  2770:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  2771:   
1.145     brouard  2772:   for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */ 
                   2773:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   2774:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
                   2775:    Ndum[ij]++; 
                   2776:  } 
1.126     brouard  2777: 
                   2778:  ij=1;
1.145     brouard  2779:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   2780:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  2781:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.145     brouard  2782:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   2783:      Tvaraff[ij]=i; /*For printing (unclear) */
1.126     brouard  2784:      ij++;
1.145     brouard  2785:    }else
                   2786:        Tvaraff[ij]=0;
1.126     brouard  2787:  }
1.131     brouard  2788:  ij--;
1.144     brouard  2789:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  2790: 
1.126     brouard  2791: }
                   2792: 
1.145     brouard  2793: 
1.126     brouard  2794: /*********** Health Expectancies ****************/
                   2795: 
1.127     brouard  2796: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
1.126     brouard  2797: 
                   2798: {
                   2799:   /* Health expectancies, no variances */
                   2800:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
                   2801:   int nhstepma, nstepma; /* Decreasing with age */
                   2802:   double age, agelim, hf;
                   2803:   double ***p3mat;
                   2804:   double eip;
                   2805: 
                   2806:   pstamp(ficreseij);
                   2807:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   2808:   fprintf(ficreseij,"# Age");
                   2809:   for(i=1; i<=nlstate;i++){
                   2810:     for(j=1; j<=nlstate;j++){
                   2811:       fprintf(ficreseij," e%1d%1d ",i,j);
                   2812:     }
                   2813:     fprintf(ficreseij," e%1d. ",i);
                   2814:   }
                   2815:   fprintf(ficreseij,"\n");
                   2816: 
                   2817:   
                   2818:   if(estepm < stepm){
                   2819:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   2820:   }
                   2821:   else  hstepm=estepm;   
                   2822:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   2823:    * This is mainly to measure the difference between two models: for example
                   2824:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   2825:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   2826:    * progression in between and thus overestimating or underestimating according
                   2827:    * to the curvature of the survival function. If, for the same date, we 
                   2828:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   2829:    * to compare the new estimate of Life expectancy with the same linear 
                   2830:    * hypothesis. A more precise result, taking into account a more precise
                   2831:    * curvature will be obtained if estepm is as small as stepm. */
                   2832: 
                   2833:   /* For example we decided to compute the life expectancy with the smallest unit */
                   2834:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   2835:      nhstepm is the number of hstepm from age to agelim 
                   2836:      nstepm is the number of stepm from age to agelin. 
                   2837:      Look at hpijx to understand the reason of that which relies in memory size
                   2838:      and note for a fixed period like estepm months */
                   2839:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   2840:      survival function given by stepm (the optimization length). Unfortunately it
                   2841:      means that if the survival funtion is printed only each two years of age and if
                   2842:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   2843:      results. So we changed our mind and took the option of the best precision.
                   2844:   */
                   2845:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   2846: 
                   2847:   agelim=AGESUP;
                   2848:   /* If stepm=6 months */
                   2849:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   2850:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   2851:     
                   2852: /* nhstepm age range expressed in number of stepm */
                   2853:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   2854:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   2855:   /* if (stepm >= YEARM) hstepm=1;*/
                   2856:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   2857:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2858: 
                   2859:   for (age=bage; age<=fage; age ++){ 
                   2860:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   2861:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   2862:     /* if (stepm >= YEARM) hstepm=1;*/
                   2863:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   2864: 
                   2865:     /* If stepm=6 months */
                   2866:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   2867:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   2868:     
                   2869:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   2870:     
                   2871:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   2872:     
                   2873:     printf("%d|",(int)age);fflush(stdout);
                   2874:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   2875:     
                   2876:     /* Computing expectancies */
                   2877:     for(i=1; i<=nlstate;i++)
                   2878:       for(j=1; j<=nlstate;j++)
                   2879:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   2880:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   2881:          
                   2882:          /* 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]);*/
                   2883: 
                   2884:        }
                   2885: 
                   2886:     fprintf(ficreseij,"%3.0f",age );
                   2887:     for(i=1; i<=nlstate;i++){
                   2888:       eip=0;
                   2889:       for(j=1; j<=nlstate;j++){
                   2890:        eip +=eij[i][j][(int)age];
                   2891:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   2892:       }
                   2893:       fprintf(ficreseij,"%9.4f", eip );
                   2894:     }
                   2895:     fprintf(ficreseij,"\n");
                   2896:     
                   2897:   }
                   2898:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2899:   printf("\n");
                   2900:   fprintf(ficlog,"\n");
                   2901:   
                   2902: }
                   2903: 
1.127     brouard  2904: 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[] )
1.126     brouard  2905: 
                   2906: {
                   2907:   /* Covariances of health expectancies eij and of total life expectancies according
                   2908:    to initial status i, ei. .
                   2909:   */
                   2910:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   2911:   int nhstepma, nstepma; /* Decreasing with age */
                   2912:   double age, agelim, hf;
                   2913:   double ***p3matp, ***p3matm, ***varhe;
                   2914:   double **dnewm,**doldm;
                   2915:   double *xp, *xm;
                   2916:   double **gp, **gm;
                   2917:   double ***gradg, ***trgradg;
                   2918:   int theta;
                   2919: 
                   2920:   double eip, vip;
                   2921: 
                   2922:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   2923:   xp=vector(1,npar);
                   2924:   xm=vector(1,npar);
                   2925:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   2926:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   2927:   
                   2928:   pstamp(ficresstdeij);
                   2929:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   2930:   fprintf(ficresstdeij,"# Age");
                   2931:   for(i=1; i<=nlstate;i++){
                   2932:     for(j=1; j<=nlstate;j++)
                   2933:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   2934:     fprintf(ficresstdeij," e%1d. ",i);
                   2935:   }
                   2936:   fprintf(ficresstdeij,"\n");
                   2937: 
                   2938:   pstamp(ficrescveij);
                   2939:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   2940:   fprintf(ficrescveij,"# Age");
                   2941:   for(i=1; i<=nlstate;i++)
                   2942:     for(j=1; j<=nlstate;j++){
                   2943:       cptj= (j-1)*nlstate+i;
                   2944:       for(i2=1; i2<=nlstate;i2++)
                   2945:        for(j2=1; j2<=nlstate;j2++){
                   2946:          cptj2= (j2-1)*nlstate+i2;
                   2947:          if(cptj2 <= cptj)
                   2948:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   2949:        }
                   2950:     }
                   2951:   fprintf(ficrescveij,"\n");
                   2952:   
                   2953:   if(estepm < stepm){
                   2954:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   2955:   }
                   2956:   else  hstepm=estepm;   
                   2957:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   2958:    * This is mainly to measure the difference between two models: for example
                   2959:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   2960:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   2961:    * progression in between and thus overestimating or underestimating according
                   2962:    * to the curvature of the survival function. If, for the same date, we 
                   2963:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   2964:    * to compare the new estimate of Life expectancy with the same linear 
                   2965:    * hypothesis. A more precise result, taking into account a more precise
                   2966:    * curvature will be obtained if estepm is as small as stepm. */
                   2967: 
                   2968:   /* For example we decided to compute the life expectancy with the smallest unit */
                   2969:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   2970:      nhstepm is the number of hstepm from age to agelim 
                   2971:      nstepm is the number of stepm from age to agelin. 
                   2972:      Look at hpijx to understand the reason of that which relies in memory size
                   2973:      and note for a fixed period like estepm months */
                   2974:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   2975:      survival function given by stepm (the optimization length). Unfortunately it
                   2976:      means that if the survival funtion is printed only each two years of age and if
                   2977:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   2978:      results. So we changed our mind and took the option of the best precision.
                   2979:   */
                   2980:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   2981: 
                   2982:   /* If stepm=6 months */
                   2983:   /* nhstepm age range expressed in number of stepm */
                   2984:   agelim=AGESUP;
                   2985:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   2986:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   2987:   /* if (stepm >= YEARM) hstepm=1;*/
                   2988:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   2989:   
                   2990:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2991:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2992:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   2993:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   2994:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   2995:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   2996: 
                   2997:   for (age=bage; age<=fage; age ++){ 
                   2998:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   2999:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3000:     /* if (stepm >= YEARM) hstepm=1;*/
                   3001:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3002: 
                   3003:     /* If stepm=6 months */
                   3004:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3005:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3006:     
                   3007:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3008: 
                   3009:     /* Computing  Variances of health expectancies */
                   3010:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3011:        decrease memory allocation */
                   3012:     for(theta=1; theta <=npar; theta++){
                   3013:       for(i=1; i<=npar; i++){ 
                   3014:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3015:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3016:       }
                   3017:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3018:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3019:   
                   3020:       for(j=1; j<= nlstate; j++){
                   3021:        for(i=1; i<=nlstate; i++){
                   3022:          for(h=0; h<=nhstepm-1; h++){
                   3023:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3024:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3025:          }
                   3026:        }
                   3027:       }
                   3028:      
                   3029:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3030:        for(h=0; h<=nhstepm-1; h++){
                   3031:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3032:        }
                   3033:     }/* End theta */
                   3034:     
                   3035:     
                   3036:     for(h=0; h<=nhstepm-1; h++)
                   3037:       for(j=1; j<=nlstate*nlstate;j++)
                   3038:        for(theta=1; theta <=npar; theta++)
                   3039:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3040:     
                   3041: 
                   3042:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3043:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3044:        varhe[ij][ji][(int)age] =0.;
                   3045: 
                   3046:      printf("%d|",(int)age);fflush(stdout);
                   3047:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3048:      for(h=0;h<=nhstepm-1;h++){
                   3049:       for(k=0;k<=nhstepm-1;k++){
                   3050:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3051:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3052:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3053:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3054:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3055:       }
                   3056:     }
                   3057: 
                   3058:     /* Computing expectancies */
                   3059:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3060:     for(i=1; i<=nlstate;i++)
                   3061:       for(j=1; j<=nlstate;j++)
                   3062:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3063:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3064:          
                   3065:          /* 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]);*/
                   3066: 
                   3067:        }
                   3068: 
                   3069:     fprintf(ficresstdeij,"%3.0f",age );
                   3070:     for(i=1; i<=nlstate;i++){
                   3071:       eip=0.;
                   3072:       vip=0.;
                   3073:       for(j=1; j<=nlstate;j++){
                   3074:        eip += eij[i][j][(int)age];
                   3075:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3076:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3077:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3078:       }
                   3079:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3080:     }
                   3081:     fprintf(ficresstdeij,"\n");
                   3082: 
                   3083:     fprintf(ficrescveij,"%3.0f",age );
                   3084:     for(i=1; i<=nlstate;i++)
                   3085:       for(j=1; j<=nlstate;j++){
                   3086:        cptj= (j-1)*nlstate+i;
                   3087:        for(i2=1; i2<=nlstate;i2++)
                   3088:          for(j2=1; j2<=nlstate;j2++){
                   3089:            cptj2= (j2-1)*nlstate+i2;
                   3090:            if(cptj2 <= cptj)
                   3091:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3092:          }
                   3093:       }
                   3094:     fprintf(ficrescveij,"\n");
                   3095:    
                   3096:   }
                   3097:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3098:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3099:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3100:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3101:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3102:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3103:   printf("\n");
                   3104:   fprintf(ficlog,"\n");
                   3105: 
                   3106:   free_vector(xm,1,npar);
                   3107:   free_vector(xp,1,npar);
                   3108:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3109:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3110:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3111: }
                   3112: 
                   3113: /************ Variance ******************/
                   3114: 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[])
                   3115: {
                   3116:   /* Variance of health expectancies */
                   3117:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3118:   /* double **newm;*/
                   3119:   double **dnewm,**doldm;
                   3120:   double **dnewmp,**doldmp;
                   3121:   int i, j, nhstepm, hstepm, h, nstepm ;
                   3122:   int k, cptcode;
                   3123:   double *xp;
                   3124:   double **gp, **gm;  /* for var eij */
                   3125:   double ***gradg, ***trgradg; /*for var eij */
                   3126:   double **gradgp, **trgradgp; /* for var p point j */
                   3127:   double *gpp, *gmp; /* for var p point j */
                   3128:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   3129:   double ***p3mat;
                   3130:   double age,agelim, hf;
                   3131:   double ***mobaverage;
                   3132:   int theta;
                   3133:   char digit[4];
                   3134:   char digitp[25];
                   3135: 
                   3136:   char fileresprobmorprev[FILENAMELENGTH];
                   3137: 
                   3138:   if(popbased==1){
                   3139:     if(mobilav!=0)
                   3140:       strcpy(digitp,"-populbased-mobilav-");
                   3141:     else strcpy(digitp,"-populbased-nomobil-");
                   3142:   }
                   3143:   else 
                   3144:     strcpy(digitp,"-stablbased-");
                   3145: 
                   3146:   if (mobilav!=0) {
                   3147:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3148:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   3149:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3150:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3151:     }
                   3152:   }
                   3153: 
                   3154:   strcpy(fileresprobmorprev,"prmorprev"); 
                   3155:   sprintf(digit,"%-d",ij);
                   3156:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   3157:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   3158:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   3159:   strcat(fileresprobmorprev,fileres);
                   3160:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   3161:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   3162:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   3163:   }
                   3164:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3165:  
                   3166:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3167:   pstamp(ficresprobmorprev);
                   3168:   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);
                   3169:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   3170:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3171:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   3172:     for(i=1; i<=nlstate;i++)
                   3173:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   3174:   }  
                   3175:   fprintf(ficresprobmorprev,"\n");
                   3176:   fprintf(ficgp,"\n# Routine varevsij");
                   3177:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   3178:   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");
                   3179:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   3180: /*   } */
                   3181:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3182:   pstamp(ficresvij);
                   3183:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   3184:   if(popbased==1)
1.128     brouard  3185:     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);
1.126     brouard  3186:   else
                   3187:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   3188:   fprintf(ficresvij,"# Age");
                   3189:   for(i=1; i<=nlstate;i++)
                   3190:     for(j=1; j<=nlstate;j++)
                   3191:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   3192:   fprintf(ficresvij,"\n");
                   3193: 
                   3194:   xp=vector(1,npar);
                   3195:   dnewm=matrix(1,nlstate,1,npar);
                   3196:   doldm=matrix(1,nlstate,1,nlstate);
                   3197:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   3198:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3199: 
                   3200:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   3201:   gpp=vector(nlstate+1,nlstate+ndeath);
                   3202:   gmp=vector(nlstate+1,nlstate+ndeath);
                   3203:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   3204:   
                   3205:   if(estepm < stepm){
                   3206:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3207:   }
                   3208:   else  hstepm=estepm;   
                   3209:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3210:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3211:      nhstepm is the number of hstepm from age to agelim 
                   3212:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  3213:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  3214:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3215:      survival function given by stepm (the optimization length). Unfortunately it
                   3216:      means that if the survival funtion is printed every two years of age and if
                   3217:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3218:      results. So we changed our mind and took the option of the best precision.
                   3219:   */
                   3220:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3221:   agelim = AGESUP;
                   3222:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3223:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3224:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3225:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3226:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   3227:     gp=matrix(0,nhstepm,1,nlstate);
                   3228:     gm=matrix(0,nhstepm,1,nlstate);
                   3229: 
                   3230: 
                   3231:     for(theta=1; theta <=npar; theta++){
                   3232:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   3233:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3234:       }
                   3235:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3236:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3237: 
                   3238:       if (popbased==1) {
                   3239:        if(mobilav ==0){
                   3240:          for(i=1; i<=nlstate;i++)
                   3241:            prlim[i][i]=probs[(int)age][i][ij];
                   3242:        }else{ /* mobilav */ 
                   3243:          for(i=1; i<=nlstate;i++)
                   3244:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3245:        }
                   3246:       }
                   3247:   
                   3248:       for(j=1; j<= nlstate; j++){
                   3249:        for(h=0; h<=nhstepm; h++){
                   3250:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   3251:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3252:        }
                   3253:       }
                   3254:       /* This for computing probability of death (h=1 means
                   3255:          computed over hstepm matrices product = hstepm*stepm months) 
                   3256:          as a weighted average of prlim.
                   3257:       */
                   3258:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3259:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   3260:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   3261:       }    
                   3262:       /* end probability of death */
                   3263: 
                   3264:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   3265:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3266:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3267:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3268:  
                   3269:       if (popbased==1) {
                   3270:        if(mobilav ==0){
                   3271:          for(i=1; i<=nlstate;i++)
                   3272:            prlim[i][i]=probs[(int)age][i][ij];
                   3273:        }else{ /* mobilav */ 
                   3274:          for(i=1; i<=nlstate;i++)
                   3275:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3276:        }
                   3277:       }
                   3278: 
1.128     brouard  3279:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  3280:        for(h=0; h<=nhstepm; h++){
                   3281:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   3282:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3283:        }
                   3284:       }
                   3285:       /* This for computing probability of death (h=1 means
                   3286:          computed over hstepm matrices product = hstepm*stepm months) 
                   3287:          as a weighted average of prlim.
                   3288:       */
                   3289:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3290:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   3291:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   3292:       }    
                   3293:       /* end probability of death */
                   3294: 
                   3295:       for(j=1; j<= nlstate; j++) /* vareij */
                   3296:        for(h=0; h<=nhstepm; h++){
                   3297:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   3298:        }
                   3299: 
                   3300:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   3301:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   3302:       }
                   3303: 
                   3304:     } /* End theta */
                   3305: 
                   3306:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   3307: 
                   3308:     for(h=0; h<=nhstepm; h++) /* veij */
                   3309:       for(j=1; j<=nlstate;j++)
                   3310:        for(theta=1; theta <=npar; theta++)
                   3311:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3312: 
                   3313:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   3314:       for(theta=1; theta <=npar; theta++)
                   3315:        trgradgp[j][theta]=gradgp[theta][j];
                   3316:   
                   3317: 
                   3318:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3319:     for(i=1;i<=nlstate;i++)
                   3320:       for(j=1;j<=nlstate;j++)
                   3321:        vareij[i][j][(int)age] =0.;
                   3322: 
                   3323:     for(h=0;h<=nhstepm;h++){
                   3324:       for(k=0;k<=nhstepm;k++){
                   3325:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   3326:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   3327:        for(i=1;i<=nlstate;i++)
                   3328:          for(j=1;j<=nlstate;j++)
                   3329:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   3330:       }
                   3331:     }
                   3332:   
                   3333:     /* pptj */
                   3334:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   3335:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   3336:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   3337:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   3338:        varppt[j][i]=doldmp[j][i];
                   3339:     /* end ppptj */
                   3340:     /*  x centered again */
                   3341:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   3342:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   3343:  
                   3344:     if (popbased==1) {
                   3345:       if(mobilav ==0){
                   3346:        for(i=1; i<=nlstate;i++)
                   3347:          prlim[i][i]=probs[(int)age][i][ij];
                   3348:       }else{ /* mobilav */ 
                   3349:        for(i=1; i<=nlstate;i++)
                   3350:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   3351:       }
                   3352:     }
                   3353:              
                   3354:     /* This for computing probability of death (h=1 means
                   3355:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   3356:        as a weighted average of prlim.
                   3357:     */
                   3358:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3359:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   3360:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   3361:     }    
                   3362:     /* end probability of death */
                   3363: 
                   3364:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   3365:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3366:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   3367:       for(i=1; i<=nlstate;i++){
                   3368:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   3369:       }
                   3370:     } 
                   3371:     fprintf(ficresprobmorprev,"\n");
                   3372: 
                   3373:     fprintf(ficresvij,"%.0f ",age );
                   3374:     for(i=1; i<=nlstate;i++)
                   3375:       for(j=1; j<=nlstate;j++){
                   3376:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   3377:       }
                   3378:     fprintf(ficresvij,"\n");
                   3379:     free_matrix(gp,0,nhstepm,1,nlstate);
                   3380:     free_matrix(gm,0,nhstepm,1,nlstate);
                   3381:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   3382:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   3383:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3384:   } /* End age */
                   3385:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   3386:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   3387:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   3388:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145     brouard  3389:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126     brouard  3390:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  3391:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126     brouard  3392: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   3393: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   3394: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  3395:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   3396:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   3397:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  3398:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   3399:   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);
                   3400:   /*  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);
                   3401: */
                   3402: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
                   3403:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                   3404: 
                   3405:   free_vector(xp,1,npar);
                   3406:   free_matrix(doldm,1,nlstate,1,nlstate);
                   3407:   free_matrix(dnewm,1,nlstate,1,npar);
                   3408:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3409:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   3410:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3411:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3412:   fclose(ficresprobmorprev);
                   3413:   fflush(ficgp);
                   3414:   fflush(fichtm); 
                   3415: }  /* end varevsij */
                   3416: 
                   3417: /************ Variance of prevlim ******************/
                   3418: 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[])
                   3419: {
                   3420:   /* Variance of prevalence limit */
                   3421:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   3422:   double **newm;
                   3423:   double **dnewm,**doldm;
                   3424:   int i, j, nhstepm, hstepm;
                   3425:   int k, cptcode;
                   3426:   double *xp;
                   3427:   double *gp, *gm;
                   3428:   double **gradg, **trgradg;
                   3429:   double age,agelim;
                   3430:   int theta;
                   3431:   
                   3432:   pstamp(ficresvpl);
                   3433:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   3434:   fprintf(ficresvpl,"# Age");
                   3435:   for(i=1; i<=nlstate;i++)
                   3436:       fprintf(ficresvpl," %1d-%1d",i,i);
                   3437:   fprintf(ficresvpl,"\n");
                   3438: 
                   3439:   xp=vector(1,npar);
                   3440:   dnewm=matrix(1,nlstate,1,npar);
                   3441:   doldm=matrix(1,nlstate,1,nlstate);
                   3442:   
                   3443:   hstepm=1*YEARM; /* Every year of age */
                   3444:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   3445:   agelim = AGESUP;
                   3446:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3447:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3448:     if (stepm >= YEARM) hstepm=1;
                   3449:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   3450:     gradg=matrix(1,npar,1,nlstate);
                   3451:     gp=vector(1,nlstate);
                   3452:     gm=vector(1,nlstate);
                   3453: 
                   3454:     for(theta=1; theta <=npar; theta++){
                   3455:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   3456:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3457:       }
                   3458:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3459:       for(i=1;i<=nlstate;i++)
                   3460:        gp[i] = prlim[i][i];
                   3461:     
                   3462:       for(i=1; i<=npar; i++) /* Computes gradient */
                   3463:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3464:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3465:       for(i=1;i<=nlstate;i++)
                   3466:        gm[i] = prlim[i][i];
                   3467: 
                   3468:       for(i=1;i<=nlstate;i++)
                   3469:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   3470:     } /* End theta */
                   3471: 
                   3472:     trgradg =matrix(1,nlstate,1,npar);
                   3473: 
                   3474:     for(j=1; j<=nlstate;j++)
                   3475:       for(theta=1; theta <=npar; theta++)
                   3476:        trgradg[j][theta]=gradg[theta][j];
                   3477: 
                   3478:     for(i=1;i<=nlstate;i++)
                   3479:       varpl[i][(int)age] =0.;
                   3480:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   3481:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   3482:     for(i=1;i<=nlstate;i++)
                   3483:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   3484: 
                   3485:     fprintf(ficresvpl,"%.0f ",age );
                   3486:     for(i=1; i<=nlstate;i++)
                   3487:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   3488:     fprintf(ficresvpl,"\n");
                   3489:     free_vector(gp,1,nlstate);
                   3490:     free_vector(gm,1,nlstate);
                   3491:     free_matrix(gradg,1,npar,1,nlstate);
                   3492:     free_matrix(trgradg,1,nlstate,1,npar);
                   3493:   } /* End age */
                   3494: 
                   3495:   free_vector(xp,1,npar);
                   3496:   free_matrix(doldm,1,nlstate,1,npar);
                   3497:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   3498: 
                   3499: }
                   3500: 
                   3501: /************ Variance of one-step probabilities  ******************/
                   3502: 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[])
                   3503: {
                   3504:   int i, j=0,  i1, k1, l1, t, tj;
                   3505:   int k2, l2, j1,  z1;
                   3506:   int k=0,l, cptcode;
1.145     brouard  3507:   int first=1, first1, first2;
1.126     brouard  3508:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   3509:   double **dnewm,**doldm;
                   3510:   double *xp;
                   3511:   double *gp, *gm;
                   3512:   double **gradg, **trgradg;
                   3513:   double **mu;
1.145     brouard  3514:   double age,agelim, cov[NCOVMAX+1];
1.126     brouard  3515:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   3516:   int theta;
                   3517:   char fileresprob[FILENAMELENGTH];
                   3518:   char fileresprobcov[FILENAMELENGTH];
                   3519:   char fileresprobcor[FILENAMELENGTH];
                   3520:   double ***varpij;
                   3521: 
                   3522:   strcpy(fileresprob,"prob"); 
                   3523:   strcat(fileresprob,fileres);
                   3524:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   3525:     printf("Problem with resultfile: %s\n", fileresprob);
                   3526:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   3527:   }
                   3528:   strcpy(fileresprobcov,"probcov"); 
                   3529:   strcat(fileresprobcov,fileres);
                   3530:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   3531:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   3532:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   3533:   }
                   3534:   strcpy(fileresprobcor,"probcor"); 
                   3535:   strcat(fileresprobcor,fileres);
                   3536:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   3537:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   3538:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   3539:   }
                   3540:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3541:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3542:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3543:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3544:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3545:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3546:   pstamp(ficresprob);
                   3547:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   3548:   fprintf(ficresprob,"# Age");
                   3549:   pstamp(ficresprobcov);
                   3550:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   3551:   fprintf(ficresprobcov,"# Age");
                   3552:   pstamp(ficresprobcor);
                   3553:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   3554:   fprintf(ficresprobcor,"# Age");
                   3555: 
                   3556: 
                   3557:   for(i=1; i<=nlstate;i++)
                   3558:     for(j=1; j<=(nlstate+ndeath);j++){
                   3559:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   3560:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   3561:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   3562:     }  
                   3563:  /* fprintf(ficresprob,"\n");
                   3564:   fprintf(ficresprobcov,"\n");
                   3565:   fprintf(ficresprobcor,"\n");
                   3566:  */
1.131     brouard  3567:   xp=vector(1,npar);
1.126     brouard  3568:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   3569:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   3570:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   3571:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   3572:   first=1;
                   3573:   fprintf(ficgp,"\n# Routine varprob");
                   3574:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   3575:   fprintf(fichtm,"\n");
                   3576: 
                   3577:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
                   3578:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
                   3579:   file %s<br>\n",optionfilehtmcov);
                   3580:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
                   3581: and drawn. It helps understanding how is the covariance between two incidences.\
                   3582:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   3583:   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. \
                   3584: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   3585: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   3586: standard deviations wide on each axis. <br>\
                   3587:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   3588:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   3589: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   3590: 
                   3591:   cov[1]=1;
1.145     brouard  3592:   /* tj=cptcoveff; */
                   3593:   tj = (int) pow(2,cptcoveff);
1.126     brouard  3594:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   3595:   j1=0;
1.145     brouard  3596:   for(j1=1; j1<=tj;j1++){
                   3597:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   3598:     /*j1++;*/
1.126     brouard  3599:       if  (cptcovn>0) {
                   3600:        fprintf(ficresprob, "\n#********** Variable "); 
                   3601:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3602:        fprintf(ficresprob, "**********\n#\n");
                   3603:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   3604:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3605:        fprintf(ficresprobcov, "**********\n#\n");
                   3606:        
                   3607:        fprintf(ficgp, "\n#********** Variable "); 
                   3608:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3609:        fprintf(ficgp, "**********\n#\n");
                   3610:        
                   3611:        
                   3612:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   3613:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3614:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   3615:        
                   3616:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   3617:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3618:        fprintf(ficresprobcor, "**********\n#");    
                   3619:       }
                   3620:       
1.145     brouard  3621:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   3622:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   3623:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   3624:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  3625:       for (age=bage; age<=fage; age ++){ 
                   3626:        cov[2]=age;
                   3627:        for (k=1; k<=cptcovn;k++) {
1.145     brouard  3628:          cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
                   3629:                                                         * 1  1 1 1 1
                   3630:                                                         * 2  2 1 1 1
                   3631:                                                         * 3  1 2 1 1
                   3632:                                                         */
                   3633:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  3634:        }
                   3635:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
                   3636:        for (k=1; k<=cptcovprod;k++)
                   3637:          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   3638:        
                   3639:     
                   3640:        for(theta=1; theta <=npar; theta++){
                   3641:          for(i=1; i<=npar; i++)
                   3642:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   3643:          
                   3644:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   3645:          
                   3646:          k=0;
                   3647:          for(i=1; i<= (nlstate); i++){
                   3648:            for(j=1; j<=(nlstate+ndeath);j++){
                   3649:              k=k+1;
                   3650:              gp[k]=pmmij[i][j];
                   3651:            }
                   3652:          }
                   3653:          
                   3654:          for(i=1; i<=npar; i++)
                   3655:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   3656:     
                   3657:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   3658:          k=0;
                   3659:          for(i=1; i<=(nlstate); i++){
                   3660:            for(j=1; j<=(nlstate+ndeath);j++){
                   3661:              k=k+1;
                   3662:              gm[k]=pmmij[i][j];
                   3663:            }
                   3664:          }
                   3665:      
                   3666:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   3667:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   3668:        }
                   3669: 
                   3670:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   3671:          for(theta=1; theta <=npar; theta++)
                   3672:            trgradg[j][theta]=gradg[theta][j];
                   3673:        
                   3674:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   3675:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   3676: 
                   3677:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   3678:        
                   3679:        k=0;
                   3680:        for(i=1; i<=(nlstate); i++){
                   3681:          for(j=1; j<=(nlstate+ndeath);j++){
                   3682:            k=k+1;
                   3683:            mu[k][(int) age]=pmmij[i][j];
                   3684:          }
                   3685:        }
                   3686:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   3687:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   3688:            varpij[i][j][(int)age] = doldm[i][j];
                   3689: 
                   3690:        /*printf("\n%d ",(int)age);
                   3691:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   3692:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   3693:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   3694:          }*/
                   3695: 
                   3696:        fprintf(ficresprob,"\n%d ",(int)age);
                   3697:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   3698:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   3699: 
                   3700:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   3701:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   3702:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   3703:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   3704:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   3705:        }
                   3706:        i=0;
                   3707:        for (k=1; k<=(nlstate);k++){
                   3708:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  3709:            i++;
1.126     brouard  3710:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   3711:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   3712:            for (j=1; j<=i;j++){
1.145     brouard  3713:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  3714:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   3715:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   3716:            }
                   3717:          }
                   3718:        }/* end of loop for state */
                   3719:       } /* end of loop for age */
1.145     brouard  3720:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   3721:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   3722:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   3723:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   3724:       
1.126     brouard  3725:       /* Confidence intervalle of pij  */
                   3726:       /*
1.131     brouard  3727:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  3728:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   3729:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   3730:        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);
                   3731:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   3732:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   3733:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   3734:       */
                   3735: 
                   3736:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  3737:       first1=1;first2=2;
1.126     brouard  3738:       for (k2=1; k2<=(nlstate);k2++){
                   3739:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   3740:          if(l2==k2) continue;
                   3741:          j=(k2-1)*(nlstate+ndeath)+l2;
                   3742:          for (k1=1; k1<=(nlstate);k1++){
                   3743:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   3744:              if(l1==k1) continue;
                   3745:              i=(k1-1)*(nlstate+ndeath)+l1;
                   3746:              if(i<=j) continue;
                   3747:              for (age=bage; age<=fage; age ++){ 
                   3748:                if ((int)age %5==0){
                   3749:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   3750:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   3751:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   3752:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   3753:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   3754:                  c12=cv12/sqrt(v1*v2);
                   3755:                  /* Computing eigen value of matrix of covariance */
                   3756:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3757:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  3758:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  3759:                    if(first2==1){
                   3760:                      first1=0;
                   3761:                    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);
                   3762:                    }
                   3763:                    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);
                   3764:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   3765:                    /* lc2=fabs(lc2); */
1.135     brouard  3766:                  }
                   3767: 
1.126     brouard  3768:                  /* Eigen vectors */
                   3769:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   3770:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   3771:                  v21=(lc1-v1)/cv12*v11;
                   3772:                  v12=-v21;
                   3773:                  v22=v11;
                   3774:                  tnalp=v21/v11;
                   3775:                  if(first1==1){
                   3776:                    first1=0;
                   3777:                    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);
                   3778:                  }
                   3779:                  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);
                   3780:                  /*printf(fignu*/
                   3781:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   3782:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   3783:                  if(first==1){
                   3784:                    first=0;
                   3785:                    fprintf(ficgp,"\nset parametric;unset label");
                   3786:                    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);
1.145     brouard  3787:                    fprintf(ficgp,"\nset ter png small size 320, 240");
1.126     brouard  3788:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   3789:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
                   3790: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                   3791:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                   3792:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   3793:                    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   3794:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   3795:                    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   3796:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   3797:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   3798:                    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",\
                   3799:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   3800:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   3801:                  }else{
                   3802:                    first=0;
                   3803:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   3804:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   3805:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   3806:                    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",\
                   3807:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   3808:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   3809:                  }/* if first */
                   3810:                } /* age mod 5 */
                   3811:              } /* end loop age */
                   3812:              fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   3813:              first=1;
                   3814:            } /*l12 */
                   3815:          } /* k12 */
                   3816:        } /*l1 */
                   3817:       }/* k1 */
1.145     brouard  3818:       /* } /* loop covariates */
1.126     brouard  3819:   }
                   3820:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   3821:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   3822:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   3823:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   3824:   free_vector(xp,1,npar);
                   3825:   fclose(ficresprob);
                   3826:   fclose(ficresprobcov);
                   3827:   fclose(ficresprobcor);
                   3828:   fflush(ficgp);
                   3829:   fflush(fichtmcov);
                   3830: }
                   3831: 
                   3832: 
                   3833: /******************* Printing html file ***********/
                   3834: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                   3835:                  int lastpass, int stepm, int weightopt, char model[],\
                   3836:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   3837:                  int popforecast, int estepm ,\
                   3838:                  double jprev1, double mprev1,double anprev1, \
                   3839:                  double jprev2, double mprev2,double anprev2){
                   3840:   int jj1, k1, i1, cpt;
                   3841: 
                   3842:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   3843:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   3844: </ul>");
                   3845:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   3846:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
                   3847:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
                   3848:    fprintf(fichtm,"\
                   3849:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   3850:           stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
                   3851:    fprintf(fichtm,"\
                   3852:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   3853:           subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
                   3854:    fprintf(fichtm,"\
1.128     brouard  3855:  - (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): \
1.126     brouard  3856:    <a href=\"%s\">%s</a> <br>\n",
                   3857:           estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
                   3858:    fprintf(fichtm,"\
                   3859:  - Population projections by age and states: \
                   3860:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
                   3861: 
                   3862: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   3863: 
1.145     brouard  3864:  m=pow(2,cptcoveff);
1.126     brouard  3865:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   3866: 
                   3867:  jj1=0;
                   3868:  for(k1=1; k1<=m;k1++){
                   3869:    for(i1=1; i1<=ncodemax[k1];i1++){
                   3870:      jj1++;
                   3871:      if (cptcovn > 0) {
                   3872:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   3873:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   3874:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   3875:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   3876:      }
                   3877:      /* Pij */
1.145     brouard  3878:      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> \
                   3879: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
1.126     brouard  3880:      /* Quasi-incidences */
                   3881:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145     brouard  3882:  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> \
                   3883: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
1.126     brouard  3884:        /* Period (stable) prevalence in each health state */
                   3885:        for(cpt=1; cpt<nlstate;cpt++){
1.145     brouard  3886:         fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d_%d.png\">%s%d_%d.png</a><br> \
                   3887: <img src=\"%s%d_%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
1.126     brouard  3888:        }
                   3889:      for(cpt=1; cpt<=nlstate;cpt++) {
                   3890:         fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \
                   3891: <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
                   3892:      }
                   3893:    } /* end i1 */
                   3894:  }/* End k1 */
                   3895:  fprintf(fichtm,"</ul>");
                   3896: 
                   3897: 
                   3898:  fprintf(fichtm,"\
                   3899: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
                   3900:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
                   3901: 
                   3902:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   3903:         subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
                   3904:  fprintf(fichtm,"\
                   3905:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   3906:         subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
                   3907: 
                   3908:  fprintf(fichtm,"\
                   3909:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   3910:         subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
                   3911:  fprintf(fichtm,"\
                   3912:  - 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): \
                   3913:    <a href=\"%s\">%s</a> <br>\n</li>",
                   3914:           estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
                   3915:  fprintf(fichtm,"\
                   3916:  - (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): \
                   3917:    <a href=\"%s\">%s</a> <br>\n</li>",
                   3918:           estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
                   3919:  fprintf(fichtm,"\
1.128     brouard  3920:  - 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",
1.126     brouard  3921:         estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
                   3922:  fprintf(fichtm,"\
1.128     brouard  3923:  - 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",
                   3924:         estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126     brouard  3925:  fprintf(fichtm,"\
                   3926:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   3927:         subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
                   3928: 
                   3929: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   3930: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   3931: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   3932: /*     <br>",fileres,fileres,fileres,fileres); */
                   3933: /*  else  */
                   3934: /*    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); */
                   3935:  fflush(fichtm);
                   3936:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   3937: 
1.145     brouard  3938:  m=pow(2,cptcoveff);
1.126     brouard  3939:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   3940: 
                   3941:  jj1=0;
                   3942:  for(k1=1; k1<=m;k1++){
                   3943:    for(i1=1; i1<=ncodemax[k1];i1++){
                   3944:      jj1++;
                   3945:      if (cptcovn > 0) {
                   3946:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   3947:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   3948:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   3949:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   3950:      }
                   3951:      for(cpt=1; cpt<=nlstate;cpt++) {
                   3952:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145     brouard  3953: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
                   3954: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
1.126     brouard  3955:      }
                   3956:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  3957: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   3958: true period expectancies (those weighted with period prevalences are also\
                   3959:  drawn in addition to the population based expectancies computed using\
                   3960:  observed and cahotic prevalences: %s%d.png<br>\
1.126     brouard  3961: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
                   3962:    } /* end i1 */
                   3963:  }/* End k1 */
                   3964:  fprintf(fichtm,"</ul>");
                   3965:  fflush(fichtm);
                   3966: }
                   3967: 
                   3968: /******************* Gnuplot file **************/
                   3969: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   3970: 
                   3971:   char dirfileres[132],optfileres[132];
1.130     brouard  3972:   int m0,cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
                   3973:   int ng=0;
1.126     brouard  3974: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   3975: /*     printf("Problem with file %s",optionfilegnuplot); */
                   3976: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   3977: /*   } */
                   3978: 
                   3979:   /*#ifdef windows */
                   3980:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   3981:     /*#endif */
                   3982:   m=pow(2,cptcoveff);
                   3983: 
                   3984:   strcpy(dirfileres,optionfilefiname);
                   3985:   strcpy(optfileres,"vpl");
                   3986:  /* 1eme*/
                   3987:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  3988:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   3989:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
                   3990:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126     brouard  3991:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   3992: set ylabel \"Probability\" \n\
1.145     brouard  3993: set ter png small size 320, 240\n\
1.126     brouard  3994: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
                   3995: 
                   3996:      for (i=1; i<= nlstate ; i ++) {
                   3997:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
1.131     brouard  3998:        else        fprintf(ficgp," \%%*lf (\%%*lf)");
1.126     brouard  3999:      }
1.145     brouard  4000:      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);
1.126     brouard  4001:      for (i=1; i<= nlstate ; i ++) {
                   4002:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
                   4003:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   4004:      } 
1.145     brouard  4005:      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); 
1.126     brouard  4006:      for (i=1; i<= nlstate ; i ++) {
                   4007:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
                   4008:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   4009:      }  
1.145     brouard  4010:      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));
1.126     brouard  4011:    }
                   4012:   }
                   4013:   /*2 eme*/
                   4014:   
                   4015:   for (k1=1; k1<= m ; k1 ++) { 
                   4016:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145     brouard  4017:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126     brouard  4018:     
                   4019:     for (i=1; i<= nlstate+1 ; i ++) {
                   4020:       k=2*i;
                   4021:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
                   4022:       for (j=1; j<= nlstate+1 ; j ++) {
                   4023:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   4024:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   4025:       }   
                   4026:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
                   4027:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
                   4028:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
                   4029:       for (j=1; j<= nlstate+1 ; j ++) {
                   4030:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   4031:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   4032:       }   
1.145     brouard  4033:       fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126     brouard  4034:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
                   4035:       for (j=1; j<= nlstate+1 ; j ++) {
                   4036:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   4037:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   4038:       }   
1.145     brouard  4039:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   4040:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126     brouard  4041:     }
                   4042:   }
                   4043:   
                   4044:   /*3eme*/
                   4045:   
                   4046:   for (k1=1; k1<= m ; k1 ++) { 
                   4047:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4048:       /*       k=2+nlstate*(2*cpt-2); */
                   4049:       k=2+(nlstate+1)*(cpt-1);
                   4050:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145     brouard  4051:       fprintf(ficgp,"set ter png small size 320, 240\n\
1.126     brouard  4052: 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);
                   4053:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4054:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4055:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4056:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4057:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4058:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4059:        
                   4060:       */
                   4061:       for (i=1; i< nlstate ; i ++) {
                   4062:        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);
                   4063:        /*      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);*/
                   4064:        
                   4065:       } 
                   4066:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
                   4067:     }
                   4068:   }
                   4069:   
                   4070:   /* CV preval stable (period) */
                   4071:   for (k1=1; k1<= m ; k1 ++) { 
                   4072:     for (cpt=1; cpt<=nlstate ; cpt ++) {
                   4073:       k=3;
1.145     brouard  4074:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126     brouard  4075:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145     brouard  4076: set ter png small size 320, 240\n\
1.126     brouard  4077: unset log y\n\
                   4078: plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);
                   4079:       
                   4080:       for (i=1; i< nlstate ; i ++)
                   4081:        fprintf(ficgp,"+$%d",k+i+1);
                   4082:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
                   4083:       
                   4084:       l=3+(nlstate+ndeath)*cpt;
                   4085:       fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
                   4086:       for (i=1; i< nlstate ; i ++) {
                   4087:        l=3+(nlstate+ndeath)*cpt;
                   4088:        fprintf(ficgp,"+$%d",l+i+1);
                   4089:       }
                   4090:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);   
                   4091:     } 
                   4092:   }  
                   4093:   
                   4094:   /* proba elementaires */
                   4095:   for(i=1,jk=1; i <=nlstate; i++){
                   4096:     for(k=1; k <=(nlstate+ndeath); k++){
                   4097:       if (k != i) {
                   4098:        for(j=1; j <=ncovmodel; j++){
                   4099:          fprintf(ficgp,"p%d=%f ",jk,p[jk]);
                   4100:          jk++; 
                   4101:          fprintf(ficgp,"\n");
                   4102:        }
                   4103:       }
                   4104:     }
                   4105:    }
1.145     brouard  4106:   /*goto avoid;*/
1.126     brouard  4107:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
                   4108:      for(jk=1; jk <=m; jk++) {
1.145     brouard  4109:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
1.126     brouard  4110:        if (ng==2)
                   4111:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   4112:        else
                   4113:         fprintf(ficgp,"\nset title \"Probability\"\n");
1.145     brouard  4114:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  4115:        i=1;
                   4116:        for(k2=1; k2<=nlstate; k2++) {
                   4117:         k3=i;
                   4118:         for(k=1; k<=(nlstate+ndeath); k++) {
                   4119:           if (k != k2){
                   4120:             if(ng==2)
                   4121:               fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   4122:             else
                   4123:               fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141     brouard  4124:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.126     brouard  4125:             for(j=3; j <=ncovmodel; j++) {
1.145     brouard  4126:               /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
                   4127:               /*        /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
                   4128:               /*        ij++; */
                   4129:               /* } */
                   4130:               /* else */
1.126     brouard  4131:                 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   4132:             }
                   4133:             fprintf(ficgp,")/(1");
                   4134:             
                   4135:             for(k1=1; k1 <=nlstate; k1++){   
                   4136:               fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   4137:               ij=1;
                   4138:               for(j=3; j <=ncovmodel; j++){
1.145     brouard  4139:                 /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
                   4140:                 /*   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
                   4141:                 /*   ij++; */
                   4142:                 /* } */
                   4143:                 /* else */
1.126     brouard  4144:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   4145:               }
                   4146:               fprintf(ficgp,")");
                   4147:             }
                   4148:             fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   4149:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   4150:             i=i+ncovmodel;
                   4151:           }
                   4152:         } /* end k */
                   4153:        } /* end k2 */
                   4154:      } /* end jk */
                   4155:    } /* end ng */
1.145     brouard  4156:  avoid:
1.126     brouard  4157:    fflush(ficgp); 
                   4158: }  /* end gnuplot */
                   4159: 
                   4160: 
                   4161: /*************** Moving average **************/
                   4162: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   4163: 
                   4164:   int i, cpt, cptcod;
                   4165:   int modcovmax =1;
                   4166:   int mobilavrange, mob;
                   4167:   double age;
                   4168: 
                   4169:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   4170:                           a covariate has 2 modalities */
                   4171:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   4172: 
                   4173:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   4174:     if(mobilav==1) mobilavrange=5; /* default */
                   4175:     else mobilavrange=mobilav;
                   4176:     for (age=bage; age<=fage; age++)
                   4177:       for (i=1; i<=nlstate;i++)
                   4178:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   4179:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   4180:     /* We keep the original values on the extreme ages bage, fage and for 
                   4181:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   4182:        we use a 5 terms etc. until the borders are no more concerned. 
                   4183:     */ 
                   4184:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   4185:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   4186:        for (i=1; i<=nlstate;i++){
                   4187:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   4188:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   4189:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   4190:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   4191:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   4192:              }
                   4193:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   4194:          }
                   4195:        }
                   4196:       }/* end age */
                   4197:     }/* end mob */
                   4198:   }else return -1;
                   4199:   return 0;
                   4200: }/* End movingaverage */
                   4201: 
                   4202: 
                   4203: /************** Forecasting ******************/
                   4204: 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){
                   4205:   /* proj1, year, month, day of starting projection 
                   4206:      agemin, agemax range of age
                   4207:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   4208:      anproj2 year of en of projection (same day and month as proj1).
                   4209:   */
                   4210:   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
                   4211:   int *popage;
                   4212:   double agec; /* generic age */
                   4213:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   4214:   double *popeffectif,*popcount;
                   4215:   double ***p3mat;
                   4216:   double ***mobaverage;
                   4217:   char fileresf[FILENAMELENGTH];
                   4218: 
                   4219:   agelim=AGESUP;
                   4220:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4221:  
                   4222:   strcpy(fileresf,"f"); 
                   4223:   strcat(fileresf,fileres);
                   4224:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   4225:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   4226:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   4227:   }
                   4228:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   4229:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   4230: 
                   4231:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4232: 
                   4233:   if (mobilav!=0) {
                   4234:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4235:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4236:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4237:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4238:     }
                   4239:   }
                   4240: 
                   4241:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4242:   if (stepm<=12) stepsize=1;
                   4243:   if(estepm < stepm){
                   4244:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4245:   }
                   4246:   else  hstepm=estepm;   
                   4247: 
                   4248:   hstepm=hstepm/stepm; 
                   4249:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   4250:                                fractional in yp1 */
                   4251:   anprojmean=yp;
                   4252:   yp2=modf((yp1*12),&yp);
                   4253:   mprojmean=yp;
                   4254:   yp1=modf((yp2*30.5),&yp);
                   4255:   jprojmean=yp;
                   4256:   if(jprojmean==0) jprojmean=1;
                   4257:   if(mprojmean==0) jprojmean=1;
                   4258: 
                   4259:   i1=cptcoveff;
                   4260:   if (cptcovn < 1){i1=1;}
                   4261:   
                   4262:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   4263:   
                   4264:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   4265: 
                   4266: /*           if (h==(int)(YEARM*yearp)){ */
                   4267:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   4268:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4269:       k=k+1;
                   4270:       fprintf(ficresf,"\n#******");
                   4271:       for(j=1;j<=cptcoveff;j++) {
                   4272:        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]]);
                   4273:       }
                   4274:       fprintf(ficresf,"******\n");
                   4275:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   4276:       for(j=1; j<=nlstate+ndeath;j++){ 
                   4277:        for(i=1; i<=nlstate;i++)              
                   4278:           fprintf(ficresf," p%d%d",i,j);
                   4279:        fprintf(ficresf," p.%d",j);
                   4280:       }
                   4281:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   4282:        fprintf(ficresf,"\n");
                   4283:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   4284: 
                   4285:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   4286:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   4287:          nhstepm = nhstepm/hstepm; 
                   4288:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4289:          oldm=oldms;savm=savms;
                   4290:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4291:        
                   4292:          for (h=0; h<=nhstepm; h++){
                   4293:            if (h*hstepm/YEARM*stepm ==yearp) {
                   4294:               fprintf(ficresf,"\n");
                   4295:               for(j=1;j<=cptcoveff;j++) 
                   4296:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4297:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   4298:            } 
                   4299:            for(j=1; j<=nlstate+ndeath;j++) {
                   4300:              ppij=0.;
                   4301:              for(i=1; i<=nlstate;i++) {
                   4302:                if (mobilav==1) 
                   4303:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   4304:                else {
                   4305:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   4306:                }
                   4307:                if (h*hstepm/YEARM*stepm== yearp) {
                   4308:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   4309:                }
                   4310:              } /* end i */
                   4311:              if (h*hstepm/YEARM*stepm==yearp) {
                   4312:                fprintf(ficresf," %.3f", ppij);
                   4313:              }
                   4314:            }/* end j */
                   4315:          } /* end h */
                   4316:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4317:        } /* end agec */
                   4318:       } /* end yearp */
                   4319:     } /* end cptcod */
                   4320:   } /* end  cptcov */
                   4321:        
                   4322:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4323: 
                   4324:   fclose(ficresf);
                   4325: }
                   4326: 
                   4327: /************** Forecasting *****not tested NB*************/
                   4328: 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){
                   4329:   
                   4330:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   4331:   int *popage;
                   4332:   double calagedatem, agelim, kk1, kk2;
                   4333:   double *popeffectif,*popcount;
                   4334:   double ***p3mat,***tabpop,***tabpopprev;
                   4335:   double ***mobaverage;
                   4336:   char filerespop[FILENAMELENGTH];
                   4337: 
                   4338:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4339:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4340:   agelim=AGESUP;
                   4341:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   4342:   
                   4343:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4344:   
                   4345:   
                   4346:   strcpy(filerespop,"pop"); 
                   4347:   strcat(filerespop,fileres);
                   4348:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   4349:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   4350:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   4351:   }
                   4352:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   4353:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   4354: 
                   4355:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4356: 
                   4357:   if (mobilav!=0) {
                   4358:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4359:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4360:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4361:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4362:     }
                   4363:   }
                   4364: 
                   4365:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4366:   if (stepm<=12) stepsize=1;
                   4367:   
                   4368:   agelim=AGESUP;
                   4369:   
                   4370:   hstepm=1;
                   4371:   hstepm=hstepm/stepm; 
                   4372:   
                   4373:   if (popforecast==1) {
                   4374:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   4375:       printf("Problem with population file : %s\n",popfile);exit(0);
                   4376:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   4377:     } 
                   4378:     popage=ivector(0,AGESUP);
                   4379:     popeffectif=vector(0,AGESUP);
                   4380:     popcount=vector(0,AGESUP);
                   4381:     
                   4382:     i=1;   
                   4383:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   4384:    
                   4385:     imx=i;
                   4386:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   4387:   }
                   4388: 
                   4389:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   4390:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4391:       k=k+1;
                   4392:       fprintf(ficrespop,"\n#******");
                   4393:       for(j=1;j<=cptcoveff;j++) {
                   4394:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4395:       }
                   4396:       fprintf(ficrespop,"******\n");
                   4397:       fprintf(ficrespop,"# Age");
                   4398:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   4399:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   4400:       
                   4401:       for (cpt=0; cpt<=0;cpt++) { 
                   4402:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4403:        
                   4404:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4405:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4406:          nhstepm = nhstepm/hstepm; 
                   4407:          
                   4408:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4409:          oldm=oldms;savm=savms;
                   4410:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4411:        
                   4412:          for (h=0; h<=nhstepm; h++){
                   4413:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4414:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4415:            } 
                   4416:            for(j=1; j<=nlstate+ndeath;j++) {
                   4417:              kk1=0.;kk2=0;
                   4418:              for(i=1; i<=nlstate;i++) {              
                   4419:                if (mobilav==1) 
                   4420:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   4421:                else {
                   4422:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   4423:                }
                   4424:              }
                   4425:              if (h==(int)(calagedatem+12*cpt)){
                   4426:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   4427:                  /*fprintf(ficrespop," %.3f", kk1);
                   4428:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   4429:              }
                   4430:            }
                   4431:            for(i=1; i<=nlstate;i++){
                   4432:              kk1=0.;
                   4433:                for(j=1; j<=nlstate;j++){
                   4434:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   4435:                }
                   4436:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   4437:            }
                   4438: 
                   4439:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   4440:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   4441:          }
                   4442:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4443:        }
                   4444:       }
                   4445:  
                   4446:   /******/
                   4447: 
                   4448:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   4449:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4450:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4451:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4452:          nhstepm = nhstepm/hstepm; 
                   4453:          
                   4454:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4455:          oldm=oldms;savm=savms;
                   4456:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4457:          for (h=0; h<=nhstepm; h++){
                   4458:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4459:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4460:            } 
                   4461:            for(j=1; j<=nlstate+ndeath;j++) {
                   4462:              kk1=0.;kk2=0;
                   4463:              for(i=1; i<=nlstate;i++) {              
                   4464:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   4465:              }
                   4466:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   4467:            }
                   4468:          }
                   4469:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4470:        }
                   4471:       }
                   4472:    } 
                   4473:   }
                   4474:  
                   4475:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4476: 
                   4477:   if (popforecast==1) {
                   4478:     free_ivector(popage,0,AGESUP);
                   4479:     free_vector(popeffectif,0,AGESUP);
                   4480:     free_vector(popcount,0,AGESUP);
                   4481:   }
                   4482:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4483:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4484:   fclose(ficrespop);
                   4485: } /* End of popforecast */
                   4486: 
                   4487: int fileappend(FILE *fichier, char *optionfich)
                   4488: {
                   4489:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   4490:     printf("Problem with file: %s\n", optionfich);
                   4491:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   4492:     return (0);
                   4493:   }
                   4494:   fflush(fichier);
                   4495:   return (1);
                   4496: }
                   4497: 
                   4498: 
                   4499: /**************** function prwizard **********************/
                   4500: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   4501: {
                   4502: 
                   4503:   /* Wizard to print covariance matrix template */
                   4504: 
                   4505:   char ca[32], cb[32], cc[32];
                   4506:   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
                   4507:   int numlinepar;
                   4508: 
                   4509:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4510:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4511:   for(i=1; i <=nlstate; i++){
                   4512:     jj=0;
                   4513:     for(j=1; j <=nlstate+ndeath; j++){
                   4514:       if(j==i) continue;
                   4515:       jj++;
                   4516:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   4517:       printf("%1d%1d",i,j);
                   4518:       fprintf(ficparo,"%1d%1d",i,j);
                   4519:       for(k=1; k<=ncovmodel;k++){
                   4520:        /*        printf(" %lf",param[i][j][k]); */
                   4521:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   4522:        printf(" 0.");
                   4523:        fprintf(ficparo," 0.");
                   4524:       }
                   4525:       printf("\n");
                   4526:       fprintf(ficparo,"\n");
                   4527:     }
                   4528:   }
                   4529:   printf("# Scales (for hessian or gradient estimation)\n");
                   4530:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   4531:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   4532:   for(i=1; i <=nlstate; i++){
                   4533:     jj=0;
                   4534:     for(j=1; j <=nlstate+ndeath; j++){
                   4535:       if(j==i) continue;
                   4536:       jj++;
                   4537:       fprintf(ficparo,"%1d%1d",i,j);
                   4538:       printf("%1d%1d",i,j);
                   4539:       fflush(stdout);
                   4540:       for(k=1; k<=ncovmodel;k++){
                   4541:        /*      printf(" %le",delti3[i][j][k]); */
                   4542:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   4543:        printf(" 0.");
                   4544:        fprintf(ficparo," 0.");
                   4545:       }
                   4546:       numlinepar++;
                   4547:       printf("\n");
                   4548:       fprintf(ficparo,"\n");
                   4549:     }
                   4550:   }
                   4551:   printf("# Covariance matrix\n");
                   4552: /* # 121 Var(a12)\n\ */
                   4553: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4554: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   4555: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   4556: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   4557: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   4558: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   4559: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   4560:   fflush(stdout);
                   4561:   fprintf(ficparo,"# Covariance matrix\n");
                   4562:   /* # 121 Var(a12)\n\ */
                   4563:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4564:   /* #   ...\n\ */
                   4565:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   4566:   
                   4567:   for(itimes=1;itimes<=2;itimes++){
                   4568:     jj=0;
                   4569:     for(i=1; i <=nlstate; i++){
                   4570:       for(j=1; j <=nlstate+ndeath; j++){
                   4571:        if(j==i) continue;
                   4572:        for(k=1; k<=ncovmodel;k++){
                   4573:          jj++;
                   4574:          ca[0]= k+'a'-1;ca[1]='\0';
                   4575:          if(itimes==1){
                   4576:            printf("#%1d%1d%d",i,j,k);
                   4577:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   4578:          }else{
                   4579:            printf("%1d%1d%d",i,j,k);
                   4580:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   4581:            /*  printf(" %.5le",matcov[i][j]); */
                   4582:          }
                   4583:          ll=0;
                   4584:          for(li=1;li <=nlstate; li++){
                   4585:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   4586:              if(lj==li) continue;
                   4587:              for(lk=1;lk<=ncovmodel;lk++){
                   4588:                ll++;
                   4589:                if(ll<=jj){
                   4590:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   4591:                  if(ll<jj){
                   4592:                    if(itimes==1){
                   4593:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   4594:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   4595:                    }else{
                   4596:                      printf(" 0.");
                   4597:                      fprintf(ficparo," 0.");
                   4598:                    }
                   4599:                  }else{
                   4600:                    if(itimes==1){
                   4601:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   4602:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   4603:                    }else{
                   4604:                      printf(" 0.");
                   4605:                      fprintf(ficparo," 0.");
                   4606:                    }
                   4607:                  }
                   4608:                }
                   4609:              } /* end lk */
                   4610:            } /* end lj */
                   4611:          } /* end li */
                   4612:          printf("\n");
                   4613:          fprintf(ficparo,"\n");
                   4614:          numlinepar++;
                   4615:        } /* end k*/
                   4616:       } /*end j */
                   4617:     } /* end i */
                   4618:   } /* end itimes */
                   4619: 
                   4620: } /* end of prwizard */
                   4621: /******************* Gompertz Likelihood ******************************/
                   4622: double gompertz(double x[])
                   4623: { 
                   4624:   double A,B,L=0.0,sump=0.,num=0.;
                   4625:   int i,n=0; /* n is the size of the sample */
                   4626: 
                   4627:   for (i=0;i<=imx-1 ; i++) {
                   4628:     sump=sump+weight[i];
                   4629:     /*    sump=sump+1;*/
                   4630:     num=num+1;
                   4631:   }
                   4632:  
                   4633:  
                   4634:   /* for (i=0; i<=imx; i++) 
                   4635:      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]);*/
                   4636: 
                   4637:   for (i=1;i<=imx ; i++)
                   4638:     {
                   4639:       if (cens[i] == 1 && wav[i]>1)
                   4640:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   4641:       
                   4642:       if (cens[i] == 0 && wav[i]>1)
                   4643:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   4644:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   4645:       
                   4646:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   4647:       if (wav[i] > 1 ) { /* ??? */
                   4648:        L=L+A*weight[i];
                   4649:        /*      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]);*/
                   4650:       }
                   4651:     }
                   4652: 
                   4653:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   4654:  
                   4655:   return -2*L*num/sump;
                   4656: }
                   4657: 
1.136     brouard  4658: #ifdef GSL
                   4659: /******************* Gompertz_f Likelihood ******************************/
                   4660: double gompertz_f(const gsl_vector *v, void *params)
                   4661: { 
                   4662:   double A,B,LL=0.0,sump=0.,num=0.;
                   4663:   double *x= (double *) v->data;
                   4664:   int i,n=0; /* n is the size of the sample */
                   4665: 
                   4666:   for (i=0;i<=imx-1 ; i++) {
                   4667:     sump=sump+weight[i];
                   4668:     /*    sump=sump+1;*/
                   4669:     num=num+1;
                   4670:   }
                   4671:  
                   4672:  
                   4673:   /* for (i=0; i<=imx; i++) 
                   4674:      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]);*/
                   4675:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   4676:   for (i=1;i<=imx ; i++)
                   4677:     {
                   4678:       if (cens[i] == 1 && wav[i]>1)
                   4679:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   4680:       
                   4681:       if (cens[i] == 0 && wav[i]>1)
                   4682:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   4683:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   4684:       
                   4685:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   4686:       if (wav[i] > 1 ) { /* ??? */
                   4687:        LL=LL+A*weight[i];
                   4688:        /*      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]);*/
                   4689:       }
                   4690:     }
                   4691: 
                   4692:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   4693:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   4694:  
                   4695:   return -2*LL*num/sump;
                   4696: }
                   4697: #endif
                   4698: 
1.126     brouard  4699: /******************* Printing html file ***********/
                   4700: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                   4701:                  int lastpass, int stepm, int weightopt, char model[],\
                   4702:                  int imx,  double p[],double **matcov,double agemortsup){
                   4703:   int i,k;
                   4704: 
                   4705:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   4706:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   4707:   for (i=1;i<=2;i++) 
                   4708:     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]));
                   4709:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
                   4710:   fprintf(fichtm,"</ul>");
                   4711: 
                   4712: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   4713: 
                   4714:  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>");
                   4715: 
                   4716:  for (k=agegomp;k<(agemortsup-2);k++) 
                   4717:    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]);
                   4718: 
                   4719:  
                   4720:   fflush(fichtm);
                   4721: }
                   4722: 
                   4723: /******************* Gnuplot file **************/
                   4724: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4725: 
                   4726:   char dirfileres[132],optfileres[132];
                   4727:   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
                   4728:   int ng;
                   4729: 
                   4730: 
                   4731:   /*#ifdef windows */
                   4732:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4733:     /*#endif */
                   4734: 
                   4735: 
                   4736:   strcpy(dirfileres,optionfilefiname);
                   4737:   strcpy(optfileres,"vpl");
                   4738:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
                   4739:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.145     brouard  4740:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
                   4741:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  4742:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   4743: 
                   4744: } 
                   4745: 
1.136     brouard  4746: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   4747: {
1.126     brouard  4748: 
1.136     brouard  4749:   /*-------- data file ----------*/
                   4750:   FILE *fic;
                   4751:   char dummy[]="                         ";
                   4752:   int i, j, n;
                   4753:   int linei, month, year,iout;
                   4754:   char line[MAXLINE], linetmp[MAXLINE];
                   4755:   char stra[80], strb[80];
                   4756:   char *stratrunc;
                   4757:   int lstra;
1.126     brouard  4758: 
                   4759: 
1.136     brouard  4760:   if((fic=fopen(datafile,"r"))==NULL)    {
                   4761:     printf("Problem while opening datafile: %s\n", datafile);return 1;
                   4762:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
                   4763:   }
1.126     brouard  4764: 
1.136     brouard  4765:   i=1;
                   4766:   linei=0;
                   4767:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   4768:     linei=linei+1;
                   4769:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   4770:       if(line[j] == '\t')
                   4771:        line[j] = ' ';
                   4772:     }
                   4773:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   4774:       ;
                   4775:     };
                   4776:     line[j+1]=0;  /* Trims blanks at end of line */
                   4777:     if(line[0]=='#'){
                   4778:       fprintf(ficlog,"Comment line\n%s\n",line);
                   4779:       printf("Comment line\n%s\n",line);
                   4780:       continue;
                   4781:     }
                   4782:     trimbb(linetmp,line); /* Trims multiple blanks in line */
                   4783:     for (j=0; line[j]!='\0';j++){
                   4784:       line[j]=linetmp[j];
                   4785:     }
                   4786:   
1.126     brouard  4787: 
1.136     brouard  4788:     for (j=maxwav;j>=1;j--){
1.137     brouard  4789:       cutv(stra, strb, line, ' '); 
1.136     brouard  4790:       if(strb[0]=='.') { /* Missing status */
                   4791:        lval=-1;
                   4792:       }else{
                   4793:        errno=0;
                   4794:        lval=strtol(strb,&endptr,10); 
                   4795:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   4796:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  4797:          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);
                   4798:          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);
1.136     brouard  4799:          return 1;
                   4800:        }
                   4801:       }
                   4802:       s[j][i]=lval;
                   4803:       
                   4804:       strcpy(line,stra);
                   4805:       cutv(stra, strb,line,' ');
                   4806:       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
                   4807:       }
1.145     brouard  4808:       else  if(iout=sscanf(strb,"%s.",dummy) != 0){
1.136     brouard  4809:        month=99;
                   4810:        year=9999;
                   4811:       }else{
1.141     brouard  4812:        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);
                   4813:        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);
1.136     brouard  4814:        return 1;
                   4815:       }
                   4816:       anint[j][i]= (double) year; 
                   4817:       mint[j][i]= (double)month; 
                   4818:       strcpy(line,stra);
                   4819:     } /* ENd Waves */
                   4820:     
                   4821:     cutv(stra, strb,line,' '); 
                   4822:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
                   4823:     }
                   4824:     else  if(iout=sscanf(strb,"%s.",dummy) != 0){
                   4825:       month=99;
                   4826:       year=9999;
                   4827:     }else{
1.141     brouard  4828:       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);
                   4829:        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);
1.136     brouard  4830:        return 1;
                   4831:     }
                   4832:     andc[i]=(double) year; 
                   4833:     moisdc[i]=(double) month; 
                   4834:     strcpy(line,stra);
                   4835:     
                   4836:     cutv(stra, strb,line,' '); 
                   4837:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
                   4838:     }
1.145     brouard  4839:     else  if(iout=sscanf(strb,"%s.", dummy) != 0){
1.136     brouard  4840:       month=99;
                   4841:       year=9999;
                   4842:     }else{
1.141     brouard  4843:       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);
                   4844:       fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);fflush(ficlog);
1.136     brouard  4845:        return 1;
                   4846:     }
                   4847:     if (year==9999) {
1.141     brouard  4848:       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);
                   4849:       fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy) but at least the year of birth should be given. Exiting.\n",strb, linei,i,line);fflush(ficlog);
1.136     brouard  4850:        return 1;
1.126     brouard  4851: 
1.136     brouard  4852:     }
                   4853:     annais[i]=(double)(year);
                   4854:     moisnais[i]=(double)(month); 
                   4855:     strcpy(line,stra);
                   4856:     
                   4857:     cutv(stra, strb,line,' '); 
                   4858:     errno=0;
                   4859:     dval=strtod(strb,&endptr); 
                   4860:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  4861:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   4862:       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);
1.136     brouard  4863:       fflush(ficlog);
                   4864:       return 1;
                   4865:     }
                   4866:     weight[i]=dval; 
                   4867:     strcpy(line,stra);
                   4868:     
                   4869:     for (j=ncovcol;j>=1;j--){
                   4870:       cutv(stra, strb,line,' '); 
                   4871:       if(strb[0]=='.') { /* Missing status */
                   4872:        lval=-1;
                   4873:       }else{
                   4874:        errno=0;
                   4875:        lval=strtol(strb,&endptr,10); 
                   4876:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  4877:          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);
                   4878:          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);
1.136     brouard  4879:          return 1;
                   4880:        }
                   4881:       }
                   4882:       if(lval <-1 || lval >1){
1.141     brouard  4883:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  4884:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   4885:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   4886:  For example, for multinomial values like 1, 2 and 3,\n \
                   4887:  build V1=0 V2=0 for the reference value (1),\n \
                   4888:         V1=1 V2=0 for (2) \n \
                   4889:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   4890:  output of IMaCh is often meaningless.\n \
                   4891:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  4892:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  4893:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   4894:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   4895:  For example, for multinomial values like 1, 2 and 3,\n \
                   4896:  build V1=0 V2=0 for the reference value (1),\n \
                   4897:         V1=1 V2=0 for (2) \n \
                   4898:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   4899:  output of IMaCh is often meaningless.\n \
                   4900:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   4901:        return 1;
                   4902:       }
                   4903:       covar[j][i]=(double)(lval);
                   4904:       strcpy(line,stra);
                   4905:     }  
                   4906:     lstra=strlen(stra);
                   4907:      
                   4908:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   4909:       stratrunc = &(stra[lstra-9]);
                   4910:       num[i]=atol(stratrunc);
                   4911:     }
                   4912:     else
                   4913:       num[i]=atol(stra);
                   4914:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   4915:       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;}*/
                   4916:     
                   4917:     i=i+1;
                   4918:   } /* End loop reading  data */
1.126     brouard  4919: 
1.136     brouard  4920:   *imax=i-1; /* Number of individuals */
                   4921:   fclose(fic);
                   4922:  
                   4923:   return (0);
                   4924:   endread:
                   4925:     printf("Exiting readdata: ");
                   4926:     fclose(fic);
                   4927:     return (1);
1.126     brouard  4928: 
                   4929: 
                   4930: 
1.136     brouard  4931: }
1.145     brouard  4932: void removespace(char *str) {
                   4933:   char *p1 = str, *p2 = str;
                   4934:   do
                   4935:     while (*p2 == ' ')
                   4936:       p2++;
                   4937:   while (*p1++ = *p2++);
                   4938: }
                   4939: 
                   4940: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
                   4941:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
                   4942:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
                   4943:    * - cptcovn or number of covariates k of the models excluding age*products =6
                   4944:    * - cptcovage number of covariates with age*products =2
                   4945:    * - cptcovs number of simple covariates
                   4946:    * - 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
                   4947:    *     which is a new column after the 9 (ncovcol) variables. 
                   4948:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   4949:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   4950:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   4951:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   4952:  */
1.136     brouard  4953: {
1.145     brouard  4954:   int i, j, k, ks;
1.136     brouard  4955:   int i1, j1, k1, k2;
                   4956:   char modelsav[80];
1.145     brouard  4957:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136     brouard  4958: 
1.145     brouard  4959:   /*removespace(model);*/
1.136     brouard  4960:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  4961:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
                   4962:     j=nbocc(model,'+'); /**< j=Number of '+' */
                   4963:     j1=nbocc(model,'*'); /**< j1=Number of '*' */
                   4964:     cptcovs=j+1-j1; /**<  Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2  */
                   4965:     cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
                   4966:                   /* including age products which are counted in cptcovage.
                   4967:                  /* but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
                   4968:     cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   4969:     cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.136     brouard  4970:     strcpy(modelsav,model); 
1.137     brouard  4971:     if (strstr(model,"AGE") !=0){
                   4972:       printf("Error. AGE must be in lower case 'age' model=%s ",model);
                   4973:       fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136     brouard  4974:       return 1;
                   4975:     }
1.141     brouard  4976:     if (strstr(model,"v") !=0){
                   4977:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   4978:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   4979:       return 1;
                   4980:     }
1.136     brouard  4981:     
1.145     brouard  4982:     /*   Design
                   4983:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   4984:      *  <          ncovcol=8                >
                   4985:      * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   4986:      *   k=  1    2      3       4     5       6      7        8
                   4987:      *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   4988:      *  covar[k,i], value of kth covariate if not including age for individual i:
                   4989:      *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   4990:      *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   4991:      *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   4992:      *  Tage[++cptcovage]=k
                   4993:      *       if products, new covar are created after ncovcol with k1
                   4994:      *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   4995:      *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   4996:      *  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
                   4997:      *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   4998:      *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   4999:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   5000:      *  <          ncovcol=8                >
                   5001:      *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   5002:      *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   5003:      *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   5004:      * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5005:      * p Tprod[1]@2={                         6, 5}
                   5006:      *p Tvard[1][1]@4= {7, 8, 5, 6}
                   5007:      * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   5008:      *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   5009:      *How to reorganize?
                   5010:      * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   5011:      * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5012:      *       {2,   1,     4,      8,    5,      6,     3,       7}
                   5013:      * Struct []
                   5014:      */
                   5015: 
1.136     brouard  5016:     /* This loop fills the array Tvar from the string 'model'.*/
                   5017:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137     brouard  5018:     /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   5019:     /*         k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   5020:     /*         k=3 V4 Tvar[k=3]= 4 (from V4) */
                   5021:     /*         k=2 V1 Tvar[k=2]= 1 (from V1) */
                   5022:     /*         k=1 Tvar[1]=2 (from V2) */
                   5023:     /*         k=5 Tvar[5] */
                   5024:     /* for (k=1; k<=cptcovn;k++) { */
                   5025:     /*         cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
                   5026:     /*         } */
                   5027:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145     brouard  5028:     /*
                   5029:      * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   5030:     for(k=cptcovt; k>=1;k--) /**< Number of covariates */
                   5031:         Tvar[k]=0;
                   5032:     cptcovage=0;
                   5033:     for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   5034:       cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   5035:                                     modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.137     brouard  5036:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136     brouard  5037:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   5038:       /*scanf("%d",i);*/
1.145     brouard  5039:       if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   5040:        cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   5041:        if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   5042:          /* covar is not filled and then is empty */
1.136     brouard  5043:          cptcovprod--;
1.145     brouard  5044:          cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   5045:          Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136     brouard  5046:          cptcovage++; /* Sums the number of covariates which include age as a product */
1.137     brouard  5047:          Tage[cptcovage]=k;  /* Tage[1] = 4 */
1.136     brouard  5048:          /*printf("stre=%s ", stre);*/
1.137     brouard  5049:        } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136     brouard  5050:          cptcovprod--;
1.145     brouard  5051:          cutl(stre,strb,strc,'V');
1.136     brouard  5052:          Tvar[k]=atoi(stre);
                   5053:          cptcovage++;
                   5054:          Tage[cptcovage]=k;
1.137     brouard  5055:        } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   5056:          /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145     brouard  5057:          cptcovn++;
                   5058:          cptcovprodnoage++;k1++;
                   5059:          cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   5060:          Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137     brouard  5061:                                  because this model-covariate is a construction we invent a new column
                   5062:                                  ncovcol + k1
                   5063:                                  If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   5064:                                  Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145     brouard  5065:          cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137     brouard  5066:          Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.145     brouard  5067:          Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   5068:          Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   5069:          k2=k2+2;
                   5070:          Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   5071:          Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137     brouard  5072:          for (i=1; i<=lastobs;i++){
                   5073:            /* Computes the new covariate which is a product of
1.145     brouard  5074:               covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136     brouard  5075:            covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137     brouard  5076:          }
                   5077:        } /* End age is not in the model */
                   5078:       } /* End if model includes a product */
1.136     brouard  5079:       else { /* no more sum */
                   5080:        /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   5081:        /*  scanf("%d",i);*/
1.145     brouard  5082:        cutl(strd,strc,strb,'V');
                   5083:        ks++; /**< Number of simple covariates */
                   5084:        cptcovn++;
                   5085:        Tvar[k]=atoi(strd);
1.136     brouard  5086:       }
1.137     brouard  5087:       strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.136     brouard  5088:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   5089:        scanf("%d",i);*/
                   5090:     } /* end of loop + */
                   5091:   } /* end model */
                   5092:   
                   5093:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   5094:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   5095: 
                   5096:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   5097:   printf("cptcovprod=%d ", cptcovprod);
                   5098:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   5099: 
                   5100:   scanf("%d ",i);*/
                   5101: 
                   5102: 
1.137     brouard  5103:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.136     brouard  5104:   endread:
                   5105:     printf("Exiting decodemodel: ");
                   5106:     return (1);
                   5107: }
                   5108: 
                   5109: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
                   5110: {
                   5111:   int i, m;
                   5112: 
                   5113:   for (i=1; i<=imx; i++) {
                   5114:     for(m=2; (m<= maxwav); m++) {
                   5115:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   5116:        anint[m][i]=9999;
                   5117:        s[m][i]=-1;
                   5118:       }
                   5119:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
                   5120:        *nberr++;
                   5121:        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);
                   5122:        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);
                   5123:        s[m][i]=-1;
                   5124:       }
                   5125:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
                   5126:        *nberr++;
                   5127:        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]); 
                   5128:        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]); 
                   5129:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   5130:       }
                   5131:     }
                   5132:   }
                   5133: 
                   5134:   for (i=1; i<=imx; i++)  {
                   5135:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   5136:     for(m=firstpass; (m<= lastpass); m++){
                   5137:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   5138:        if (s[m][i] >= nlstate+1) {
                   5139:          if(agedc[i]>0)
                   5140:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
                   5141:              agev[m][i]=agedc[i];
                   5142:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
                   5143:            else {
                   5144:              if ((int)andc[i]!=9999){
                   5145:                nbwarn++;
                   5146:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   5147:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   5148:                agev[m][i]=-1;
                   5149:              }
                   5150:            }
                   5151:        }
                   5152:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   5153:                                 years but with the precision of a month */
                   5154:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   5155:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   5156:            agev[m][i]=1;
                   5157:          else if(agev[m][i] < *agemin){ 
                   5158:            *agemin=agev[m][i];
                   5159:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   5160:          }
                   5161:          else if(agev[m][i] >*agemax){
                   5162:            *agemax=agev[m][i];
1.139     brouard  5163:            printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);
1.136     brouard  5164:          }
                   5165:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   5166:          /*     agev[m][i] = age[i]+2*m;*/
                   5167:        }
                   5168:        else { /* =9 */
                   5169:          agev[m][i]=1;
                   5170:          s[m][i]=-1;
                   5171:        }
                   5172:       }
                   5173:       else /*= 0 Unknown */
                   5174:        agev[m][i]=1;
                   5175:     }
                   5176:     
                   5177:   }
                   5178:   for (i=1; i<=imx; i++)  {
                   5179:     for(m=firstpass; (m<=lastpass); m++){
                   5180:       if (s[m][i] > (nlstate+ndeath)) {
                   5181:        *nberr++;
                   5182:        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);     
                   5183:        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);     
                   5184:        return 1;
                   5185:       }
                   5186:     }
                   5187:   }
                   5188: 
                   5189:   /*for (i=1; i<=imx; i++){
                   5190:   for (m=firstpass; (m<lastpass); m++){
                   5191:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   5192: }
                   5193: 
                   5194: }*/
                   5195: 
                   5196: 
1.139     brouard  5197:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   5198:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  5199: 
                   5200:   return (0);
                   5201:   endread:
                   5202:     printf("Exiting calandcheckages: ");
                   5203:     return (1);
                   5204: }
                   5205: 
                   5206: 
                   5207: /***********************************************/
                   5208: /**************** Main Program *****************/
                   5209: /***********************************************/
                   5210: 
                   5211: int main(int argc, char *argv[])
                   5212: {
                   5213: #ifdef GSL
                   5214:   const gsl_multimin_fminimizer_type *T;
                   5215:   size_t iteri = 0, it;
                   5216:   int rval = GSL_CONTINUE;
                   5217:   int status = GSL_SUCCESS;
                   5218:   double ssval;
                   5219: #endif
                   5220:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
                   5221:   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
                   5222:   int linei, month, year,iout;
                   5223:   int jj, ll, li, lj, lk, imk;
                   5224:   int numlinepar=0; /* Current linenumber of parameter file */
                   5225:   int itimes;
                   5226:   int NDIM=2;
                   5227:   int vpopbased=0;
                   5228: 
                   5229:   char ca[32], cb[32], cc[32];
                   5230:   /*  FILE *fichtm; *//* Html File */
                   5231:   /* FILE *ficgp;*/ /*Gnuplot File */
                   5232:   struct stat info;
                   5233:   double agedeb, agefin,hf;
                   5234:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
                   5235: 
                   5236:   double fret;
                   5237:   double **xi,tmp,delta;
                   5238: 
                   5239:   double dum; /* Dummy variable */
                   5240:   double ***p3mat;
                   5241:   double ***mobaverage;
                   5242:   int *indx;
                   5243:   char line[MAXLINE], linepar[MAXLINE];
                   5244:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
                   5245:   char pathr[MAXLINE], pathimach[MAXLINE]; 
                   5246:   char **bp, *tok, *val; /* pathtot */
                   5247:   int firstobs=1, lastobs=10;
                   5248:   int sdeb, sfin; /* Status at beginning and end */
                   5249:   int c,  h , cpt,l;
                   5250:   int ju,jl, mi;
                   5251:   int i1,j1, jk,aa,bb, stepsize, ij;
                   5252:   int jnais,jdc,jint4,jint1,jint2,jint3,*tab; 
                   5253:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   5254:   int mobilav=0,popforecast=0;
                   5255:   int hstepm, nhstepm;
                   5256:   int agemortsup;
                   5257:   float  sumlpop=0.;
                   5258:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   5259:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   5260: 
                   5261:   double bage, fage, age, agelim, agebase;
                   5262:   double ftolpl=FTOL;
                   5263:   double **prlim;
                   5264:   double ***param; /* Matrix of parameters */
                   5265:   double  *p;
                   5266:   double **matcov; /* Matrix of covariance */
                   5267:   double ***delti3; /* Scale */
                   5268:   double *delti; /* Scale */
                   5269:   double ***eij, ***vareij;
                   5270:   double **varpl; /* Variances of prevalence limits by age */
                   5271:   double *epj, vepp;
                   5272:   double kk1, kk2;
                   5273:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   5274:   double **ximort;
1.145     brouard  5275:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  5276:   int *dcwave;
                   5277: 
                   5278:   char z[1]="c", occ;
                   5279: 
                   5280:   /*char  *strt;*/
                   5281:   char strtend[80];
1.126     brouard  5282: 
                   5283:   long total_usecs;
                   5284:  
                   5285: /*   setlocale (LC_ALL, ""); */
                   5286: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   5287: /*   textdomain (PACKAGE); */
                   5288: /*   setlocale (LC_CTYPE, ""); */
                   5289: /*   setlocale (LC_MESSAGES, ""); */
                   5290: 
                   5291:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
                   5292:   (void) gettimeofday(&start_time,&tzp);
                   5293:   curr_time=start_time;
                   5294:   tm = *localtime(&start_time.tv_sec);
                   5295:   tmg = *gmtime(&start_time.tv_sec);
                   5296:   strcpy(strstart,asctime(&tm));
                   5297: 
                   5298: /*  printf("Localtime (at start)=%s",strstart); */
                   5299: /*  tp.tv_sec = tp.tv_sec +86400; */
                   5300: /*  tm = *localtime(&start_time.tv_sec); */
                   5301: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   5302: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   5303: /*   tmg.tm_hour=tmg.tm_hour + 1; */
                   5304: /*   tp.tv_sec = mktime(&tmg); */
                   5305: /*   strt=asctime(&tmg); */
                   5306: /*   printf("Time(after) =%s",strstart);  */
                   5307: /*  (void) time (&time_value);
                   5308: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   5309: *  tm = *localtime(&time_value);
                   5310: *  strstart=asctime(&tm);
                   5311: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   5312: */
                   5313: 
                   5314:   nberr=0; /* Number of errors and warnings */
                   5315:   nbwarn=0;
                   5316:   getcwd(pathcd, size);
                   5317: 
                   5318:   printf("\n%s\n%s",version,fullversion);
                   5319:   if(argc <=1){
                   5320:     printf("\nEnter the parameter file name: ");
                   5321:     fgets(pathr,FILENAMELENGTH,stdin);
                   5322:     i=strlen(pathr);
                   5323:     if(pathr[i-1]=='\n')
                   5324:       pathr[i-1]='\0';
                   5325:    for (tok = pathr; tok != NULL; ){
                   5326:       printf("Pathr |%s|\n",pathr);
                   5327:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   5328:       printf("val= |%s| pathr=%s\n",val,pathr);
                   5329:       strcpy (pathtot, val);
                   5330:       if(pathr[0] == '\0') break; /* Dirty */
                   5331:     }
                   5332:   }
                   5333:   else{
                   5334:     strcpy(pathtot,argv[1]);
                   5335:   }
                   5336:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   5337:   /*cygwin_split_path(pathtot,path,optionfile);
                   5338:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   5339:   /* cutv(path,optionfile,pathtot,'\\');*/
                   5340: 
                   5341:   /* Split argv[0], imach program to get pathimach */
                   5342:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   5343:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   5344:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   5345:  /*   strcpy(pathimach,argv[0]); */
                   5346:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   5347:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   5348:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
                   5349:   chdir(path); /* Can be a relative path */
                   5350:   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   5351:     printf("Current directory %s!\n",pathcd);
                   5352:   strcpy(command,"mkdir ");
                   5353:   strcat(command,optionfilefiname);
                   5354:   if((outcmd=system(command)) != 0){
                   5355:     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
                   5356:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   5357:     /* fclose(ficlog); */
                   5358: /*     exit(1); */
                   5359:   }
                   5360: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   5361: /*     perror("mkdir"); */
                   5362: /*   } */
                   5363: 
                   5364:   /*-------- arguments in the command line --------*/
                   5365: 
                   5366:   /* Log file */
                   5367:   strcat(filelog, optionfilefiname);
                   5368:   strcat(filelog,".log");    /* */
                   5369:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   5370:     printf("Problem with logfile %s\n",filelog);
                   5371:     goto end;
                   5372:   }
                   5373:   fprintf(ficlog,"Log filename:%s\n",filelog);
                   5374:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
                   5375:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   5376:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   5377:  path=%s \n\
                   5378:  optionfile=%s\n\
                   5379:  optionfilext=%s\n\
                   5380:  optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
                   5381: 
                   5382:   printf("Local time (at start):%s",strstart);
                   5383:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   5384:   fflush(ficlog);
                   5385: /*   (void) gettimeofday(&curr_time,&tzp); */
                   5386: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
                   5387: 
                   5388:   /* */
                   5389:   strcpy(fileres,"r");
                   5390:   strcat(fileres, optionfilefiname);
                   5391:   strcat(fileres,".txt");    /* Other files have txt extension */
                   5392: 
                   5393:   /*---------arguments file --------*/
                   5394: 
                   5395:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.149     brouard  5396:     printf("Problem with optionfile %s with errno=%s\n",optionfile,strerror(errno));
                   5397:     fprintf(ficlog,"Problem with optionfile %s with errno=%s\n",optionfile,strerror(errno));
1.126     brouard  5398:     fflush(ficlog);
1.149     brouard  5399:     /* goto end; */
                   5400:     exit(70); 
1.126     brouard  5401:   }
                   5402: 
                   5403: 
                   5404: 
                   5405:   strcpy(filereso,"o");
                   5406:   strcat(filereso,fileres);
                   5407:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   5408:     printf("Problem with Output resultfile: %s\n", filereso);
                   5409:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   5410:     fflush(ficlog);
                   5411:     goto end;
                   5412:   }
                   5413: 
                   5414:   /* Reads comments: lines beginning with '#' */
                   5415:   numlinepar=0;
                   5416:   while((c=getc(ficpar))=='#' && c!= EOF){
                   5417:     ungetc(c,ficpar);
                   5418:     fgets(line, MAXLINE, ficpar);
                   5419:     numlinepar++;
1.141     brouard  5420:     fputs(line,stdout);
1.126     brouard  5421:     fputs(line,ficparo);
                   5422:     fputs(line,ficlog);
                   5423:   }
                   5424:   ungetc(c,ficpar);
                   5425: 
                   5426:   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);
                   5427:   numlinepar++;
                   5428:   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);
                   5429:   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);
                   5430:   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);
                   5431:   fflush(ficlog);
                   5432:   while((c=getc(ficpar))=='#' && c!= EOF){
                   5433:     ungetc(c,ficpar);
                   5434:     fgets(line, MAXLINE, ficpar);
                   5435:     numlinepar++;
1.141     brouard  5436:     fputs(line, stdout);
                   5437:     //puts(line);
1.126     brouard  5438:     fputs(line,ficparo);
                   5439:     fputs(line,ficlog);
                   5440:   }
                   5441:   ungetc(c,ficpar);
                   5442: 
                   5443:    
1.145     brouard  5444:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  5445:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   5446:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   5447:      v1+v2*age+v2*v3 makes cptcovn = 3
                   5448:   */
                   5449:   if (strlen(model)>1) 
1.145     brouard  5450:     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*/
                   5451:   else
                   5452:     ncovmodel=2;
1.126     brouard  5453:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133     brouard  5454:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   5455:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  5456:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   5457:     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);
                   5458:     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);
                   5459:     fflush(stdout);
                   5460:     fclose (ficlog);
                   5461:     goto end;
                   5462:   }
1.126     brouard  5463:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5464:   delti=delti3[1][1];
                   5465:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   5466:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   5467:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   5468:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   5469:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   5470:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   5471:     fclose (ficparo);
                   5472:     fclose (ficlog);
                   5473:     goto end;
                   5474:     exit(0);
                   5475:   }
                   5476:   else if(mle==-3) {
                   5477:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   5478:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   5479:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   5480:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5481:     matcov=matrix(1,npar,1,npar);
                   5482:   }
                   5483:   else{
1.145     brouard  5484:     /* Read guessed parameters */
1.126     brouard  5485:     /* Reads comments: lines beginning with '#' */
                   5486:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5487:       ungetc(c,ficpar);
                   5488:       fgets(line, MAXLINE, ficpar);
                   5489:       numlinepar++;
1.141     brouard  5490:       fputs(line,stdout);
1.126     brouard  5491:       fputs(line,ficparo);
                   5492:       fputs(line,ficlog);
                   5493:     }
                   5494:     ungetc(c,ficpar);
                   5495:     
                   5496:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5497:     for(i=1; i <=nlstate; i++){
                   5498:       j=0;
                   5499:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   5500:        if(jj==i) continue;
                   5501:        j++;
                   5502:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   5503:        if ((i1 != i) && (j1 != j)){
                   5504:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   5505: It might be a problem of design; if ncovcol and the model are correct\n \
                   5506: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   5507:          exit(1);
                   5508:        }
                   5509:        fprintf(ficparo,"%1d%1d",i1,j1);
                   5510:        if(mle==1)
                   5511:          printf("%1d%1d",i,j);
                   5512:        fprintf(ficlog,"%1d%1d",i,j);
                   5513:        for(k=1; k<=ncovmodel;k++){
                   5514:          fscanf(ficpar," %lf",&param[i][j][k]);
                   5515:          if(mle==1){
                   5516:            printf(" %lf",param[i][j][k]);
                   5517:            fprintf(ficlog," %lf",param[i][j][k]);
                   5518:          }
                   5519:          else
                   5520:            fprintf(ficlog," %lf",param[i][j][k]);
                   5521:          fprintf(ficparo," %lf",param[i][j][k]);
                   5522:        }
                   5523:        fscanf(ficpar,"\n");
                   5524:        numlinepar++;
                   5525:        if(mle==1)
                   5526:          printf("\n");
                   5527:        fprintf(ficlog,"\n");
                   5528:        fprintf(ficparo,"\n");
                   5529:       }
                   5530:     }  
                   5531:     fflush(ficlog);
                   5532: 
1.145     brouard  5533:     /* Reads scales values */
1.126     brouard  5534:     p=param[1][1];
                   5535:     
                   5536:     /* Reads comments: lines beginning with '#' */
                   5537:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5538:       ungetc(c,ficpar);
                   5539:       fgets(line, MAXLINE, ficpar);
                   5540:       numlinepar++;
1.141     brouard  5541:       fputs(line,stdout);
1.126     brouard  5542:       fputs(line,ficparo);
                   5543:       fputs(line,ficlog);
                   5544:     }
                   5545:     ungetc(c,ficpar);
                   5546: 
                   5547:     for(i=1; i <=nlstate; i++){
                   5548:       for(j=1; j <=nlstate+ndeath-1; j++){
                   5549:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   5550:        if ((i1-i)*(j1-j)!=0){
                   5551:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   5552:          exit(1);
                   5553:        }
                   5554:        printf("%1d%1d",i,j);
                   5555:        fprintf(ficparo,"%1d%1d",i1,j1);
                   5556:        fprintf(ficlog,"%1d%1d",i1,j1);
                   5557:        for(k=1; k<=ncovmodel;k++){
                   5558:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   5559:          printf(" %le",delti3[i][j][k]);
                   5560:          fprintf(ficparo," %le",delti3[i][j][k]);
                   5561:          fprintf(ficlog," %le",delti3[i][j][k]);
                   5562:        }
                   5563:        fscanf(ficpar,"\n");
                   5564:        numlinepar++;
                   5565:        printf("\n");
                   5566:        fprintf(ficparo,"\n");
                   5567:        fprintf(ficlog,"\n");
                   5568:       }
                   5569:     }
                   5570:     fflush(ficlog);
                   5571: 
1.145     brouard  5572:     /* Reads covariance matrix */
1.126     brouard  5573:     delti=delti3[1][1];
                   5574: 
                   5575: 
                   5576:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   5577:   
                   5578:     /* Reads comments: lines beginning with '#' */
                   5579:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5580:       ungetc(c,ficpar);
                   5581:       fgets(line, MAXLINE, ficpar);
                   5582:       numlinepar++;
1.141     brouard  5583:       fputs(line,stdout);
1.126     brouard  5584:       fputs(line,ficparo);
                   5585:       fputs(line,ficlog);
                   5586:     }
                   5587:     ungetc(c,ficpar);
                   5588:   
                   5589:     matcov=matrix(1,npar,1,npar);
1.131     brouard  5590:     for(i=1; i <=npar; i++)
                   5591:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   5592:       
1.126     brouard  5593:     for(i=1; i <=npar; i++){
1.145     brouard  5594:       fscanf(ficpar,"%s",str);
1.126     brouard  5595:       if(mle==1)
                   5596:        printf("%s",str);
                   5597:       fprintf(ficlog,"%s",str);
                   5598:       fprintf(ficparo,"%s",str);
                   5599:       for(j=1; j <=i; j++){
                   5600:        fscanf(ficpar," %le",&matcov[i][j]);
                   5601:        if(mle==1){
                   5602:          printf(" %.5le",matcov[i][j]);
                   5603:        }
                   5604:        fprintf(ficlog," %.5le",matcov[i][j]);
                   5605:        fprintf(ficparo," %.5le",matcov[i][j]);
                   5606:       }
                   5607:       fscanf(ficpar,"\n");
                   5608:       numlinepar++;
                   5609:       if(mle==1)
                   5610:        printf("\n");
                   5611:       fprintf(ficlog,"\n");
                   5612:       fprintf(ficparo,"\n");
                   5613:     }
                   5614:     for(i=1; i <=npar; i++)
                   5615:       for(j=i+1;j<=npar;j++)
                   5616:        matcov[i][j]=matcov[j][i];
                   5617:     
                   5618:     if(mle==1)
                   5619:       printf("\n");
                   5620:     fprintf(ficlog,"\n");
                   5621:     
                   5622:     fflush(ficlog);
                   5623:     
                   5624:     /*-------- Rewriting parameter file ----------*/
                   5625:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   5626:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   5627:     strcat(rfileres,".");    /* */
                   5628:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   5629:     if((ficres =fopen(rfileres,"w"))==NULL) {
                   5630:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
                   5631:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
                   5632:     }
                   5633:     fprintf(ficres,"#%s\n",version);
                   5634:   }    /* End of mle != -3 */
                   5635: 
                   5636: 
                   5637:   n= lastobs;
                   5638:   num=lvector(1,n);
                   5639:   moisnais=vector(1,n);
                   5640:   annais=vector(1,n);
                   5641:   moisdc=vector(1,n);
                   5642:   andc=vector(1,n);
                   5643:   agedc=vector(1,n);
                   5644:   cod=ivector(1,n);
                   5645:   weight=vector(1,n);
                   5646:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   5647:   mint=matrix(1,maxwav,1,n);
                   5648:   anint=matrix(1,maxwav,1,n);
1.131     brouard  5649:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  5650:   tab=ivector(1,NCOVMAX);
1.144     brouard  5651:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126     brouard  5652: 
1.136     brouard  5653:   /* Reads data from file datafile */
                   5654:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   5655:     goto end;
                   5656: 
                   5657:   /* Calculation of the number of parameters from char model */
1.137     brouard  5658:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   5659:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   5660:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   5661:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   5662:        k=1 Tvar[1]=2 (from V2)
                   5663:     */
                   5664:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   5665:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   5666:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   5667:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   5668:   */
                   5669:   /* For model-covariate k tells which data-covariate to use but
                   5670:     because this model-covariate is a construction we invent a new column
                   5671:     ncovcol + k1
                   5672:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   5673:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  5674:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  5675:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   5676:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   5677:   */
1.145     brouard  5678:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   5679:   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
1.141     brouard  5680:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   5681:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  5682:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  5683:                         4 covariates (3 plus signs)
                   5684:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   5685:                      */  
1.136     brouard  5686: 
                   5687:   if(decodemodel(model, lastobs) == 1)
                   5688:     goto end;
                   5689: 
1.137     brouard  5690:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   5691:     nbwarn++;
                   5692:     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); 
                   5693:     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); 
                   5694:   }
1.136     brouard  5695:     /*  if(mle==1){*/
1.137     brouard  5696:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   5697:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  5698:   }
                   5699: 
                   5700:     /*-calculation of age at interview from date of interview and age at death -*/
                   5701:   agev=matrix(1,maxwav,1,imx);
                   5702: 
                   5703:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   5704:     goto end;
                   5705: 
1.126     brouard  5706: 
1.136     brouard  5707:   agegomp=(int)agemin;
                   5708:   free_vector(moisnais,1,n);
                   5709:   free_vector(annais,1,n);
1.126     brouard  5710:   /* free_matrix(mint,1,maxwav,1,n);
                   5711:      free_matrix(anint,1,maxwav,1,n);*/
                   5712:   free_vector(moisdc,1,n);
                   5713:   free_vector(andc,1,n);
1.145     brouard  5714:   /* */
                   5715:   
1.126     brouard  5716:   wav=ivector(1,imx);
                   5717:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   5718:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   5719:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   5720:    
                   5721:   /* Concatenates waves */
                   5722:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  5723:   /* */
                   5724:  
1.126     brouard  5725:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   5726: 
                   5727:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   5728:   ncodemax[1]=1;
1.145     brouard  5729:   Ndum =ivector(-1,NCOVMAX);  
                   5730:   if (ncovmodel > 2)
                   5731:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
                   5732: 
                   5733:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
                   5734:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
                   5735:   h=0;
                   5736: 
                   5737: 
                   5738:   /*if (cptcovn > 0) */
1.126     brouard  5739:       
1.145     brouard  5740:  
1.126     brouard  5741:   m=pow(2,cptcoveff);
                   5742:  
1.131     brouard  5743:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143     brouard  5744:     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 */ 
                   5745:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
                   5746:        for(cpt=1; cpt <=pow(2,k-1); cpt++){  /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 
1.126     brouard  5747:          h++;
1.141     brouard  5748:          if (h>m) 
1.136     brouard  5749:            h=1;
1.144     brouard  5750:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143     brouard  5751:           *     h     1     2     3     4
                   5752:           *______________________________  
                   5753:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   5754:           *     2     2     1     1     1
                   5755:           *     3 i=2 1     2     1     1
                   5756:           *     4     2     2     1     1
                   5757:           *     5 i=3 1 i=2 1     2     1
                   5758:           *     6     2     1     2     1
                   5759:           *     7 i=4 1     2     2     1
                   5760:           *     8     2     2     2     1
                   5761:           *     9 i=5 1 i=3 1 i=2 1     1
                   5762:           *    10     2     1     1     1
                   5763:           *    11 i=6 1     2     1     1
                   5764:           *    12     2     2     1     1
                   5765:           *    13 i=7 1 i=4 1     2     1    
                   5766:           *    14     2     1     2     1
                   5767:           *    15 i=8 1     2     2     1
                   5768:           *    16     2     2     2     1
                   5769:           */
1.141     brouard  5770:          codtab[h][k]=j;
1.145     brouard  5771:          /*codtab[h][Tvar[k]]=j;*/
1.130     brouard  5772:          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]]);
1.126     brouard  5773:        } 
                   5774:       }
                   5775:     }
                   5776:   } 
                   5777:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   5778:      codtab[1][2]=1;codtab[2][2]=2; */
                   5779:   /* for(i=1; i <=m ;i++){ 
                   5780:      for(k=1; k <=cptcovn; k++){
1.131     brouard  5781:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126     brouard  5782:      }
                   5783:      printf("\n");
                   5784:      }
                   5785:      scanf("%d",i);*/
1.145     brouard  5786: 
                   5787:  free_ivector(Ndum,-1,NCOVMAX);
                   5788: 
                   5789: 
1.126     brouard  5790:     
                   5791:   /*------------ gnuplot -------------*/
                   5792:   strcpy(optionfilegnuplot,optionfilefiname);
                   5793:   if(mle==-3)
                   5794:     strcat(optionfilegnuplot,"-mort");
                   5795:   strcat(optionfilegnuplot,".gp");
                   5796: 
                   5797:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   5798:     printf("Problem with file %s",optionfilegnuplot);
                   5799:   }
                   5800:   else{
                   5801:     fprintf(ficgp,"\n# %s\n", version); 
                   5802:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  5803:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   5804:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  5805:   }
                   5806:   /*  fclose(ficgp);*/
                   5807:   /*--------- index.htm --------*/
                   5808: 
                   5809:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   5810:   if(mle==-3)
                   5811:     strcat(optionfilehtm,"-mort");
                   5812:   strcat(optionfilehtm,".htm");
                   5813:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  5814:     printf("Problem with %s \n",optionfilehtm);
                   5815:     exit(0);
1.126     brouard  5816:   }
                   5817: 
                   5818:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   5819:   strcat(optionfilehtmcov,"-cov.htm");
                   5820:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   5821:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   5822:   }
                   5823:   else{
                   5824:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   5825: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   5826: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   5827:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5828:   }
                   5829: 
                   5830:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   5831: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   5832: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   5833: \n\
                   5834: <hr  size=\"2\" color=\"#EC5E5E\">\
                   5835:  <ul><li><h4>Parameter files</h4>\n\
                   5836:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   5837:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   5838:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   5839:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   5840:  - Date and time at start: %s</ul>\n",\
                   5841:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   5842:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   5843:          fileres,fileres,\
                   5844:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   5845:   fflush(fichtm);
                   5846: 
                   5847:   strcpy(pathr,path);
                   5848:   strcat(pathr,optionfilefiname);
                   5849:   chdir(optionfilefiname); /* Move to directory named optionfile */
                   5850:   
                   5851:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   5852:      and prints on file fileres'p'. */
                   5853:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   5854: 
                   5855:   fprintf(fichtm,"\n");
                   5856:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   5857: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   5858: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   5859:          imx,agemin,agemax,jmin,jmax,jmean);
                   5860:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   5861:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   5862:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   5863:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   5864:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   5865:     
                   5866:    
                   5867:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   5868:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   5869:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   5870: 
                   5871:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
                   5872: 
                   5873:   if (mle==-3){
1.136     brouard  5874:     ximort=matrix(1,NDIM,1,NDIM); 
                   5875: /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  5876:     cens=ivector(1,n);
                   5877:     ageexmed=vector(1,n);
                   5878:     agecens=vector(1,n);
                   5879:     dcwave=ivector(1,n);
                   5880:  
                   5881:     for (i=1; i<=imx; i++){
                   5882:       dcwave[i]=-1;
                   5883:       for (m=firstpass; m<=lastpass; m++)
                   5884:        if (s[m][i]>nlstate) {
                   5885:          dcwave[i]=m;
                   5886:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   5887:          break;
                   5888:        }
                   5889:     }
                   5890: 
                   5891:     for (i=1; i<=imx; i++) {
                   5892:       if (wav[i]>0){
                   5893:        ageexmed[i]=agev[mw[1][i]][i];
                   5894:        j=wav[i];
                   5895:        agecens[i]=1.; 
                   5896: 
                   5897:        if (ageexmed[i]> 1 && wav[i] > 0){
                   5898:          agecens[i]=agev[mw[j][i]][i];
                   5899:          cens[i]= 1;
                   5900:        }else if (ageexmed[i]< 1) 
                   5901:          cens[i]= -1;
                   5902:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   5903:          cens[i]=0 ;
                   5904:       }
                   5905:       else cens[i]=-1;
                   5906:     }
                   5907:     
                   5908:     for (i=1;i<=NDIM;i++) {
                   5909:       for (j=1;j<=NDIM;j++)
                   5910:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   5911:     }
                   5912:     
1.145     brouard  5913:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  5914:     /*printf("%lf %lf", p[1], p[2]);*/
                   5915:     
                   5916:     
1.136     brouard  5917: #ifdef GSL
                   5918:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
                   5919: #elsedef
1.126     brouard  5920:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  5921: #endif
1.126     brouard  5922:     strcpy(filerespow,"pow-mort"); 
                   5923:     strcat(filerespow,fileres);
                   5924:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   5925:       printf("Problem with resultfile: %s\n", filerespow);
                   5926:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   5927:     }
1.136     brouard  5928: #ifdef GSL
                   5929:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
                   5930: #elsedef
1.126     brouard  5931:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  5932: #endif
1.126     brouard  5933:     /*  for (i=1;i<=nlstate;i++)
                   5934:        for(j=1;j<=nlstate+ndeath;j++)
                   5935:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   5936:     */
                   5937:     fprintf(ficrespow,"\n");
1.136     brouard  5938: #ifdef GSL
                   5939:     /* gsl starts here */ 
                   5940:     T = gsl_multimin_fminimizer_nmsimplex;
                   5941:     gsl_multimin_fminimizer *sfm = NULL;
                   5942:     gsl_vector *ss, *x;
                   5943:     gsl_multimin_function minex_func;
                   5944: 
                   5945:     /* Initial vertex size vector */
                   5946:     ss = gsl_vector_alloc (NDIM);
                   5947:     
                   5948:     if (ss == NULL){
                   5949:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   5950:     }
                   5951:     /* Set all step sizes to 1 */
                   5952:     gsl_vector_set_all (ss, 0.001);
                   5953: 
                   5954:     /* Starting point */
1.126     brouard  5955:     
1.136     brouard  5956:     x = gsl_vector_alloc (NDIM);
                   5957:     
                   5958:     if (x == NULL){
                   5959:       gsl_vector_free(ss);
                   5960:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   5961:     }
                   5962:   
                   5963:     /* Initialize method and iterate */
                   5964:     /*     p[1]=0.0268; p[NDIM]=0.083; */
                   5965: /*     gsl_vector_set(x, 0, 0.0268); */
                   5966: /*     gsl_vector_set(x, 1, 0.083); */
                   5967:     gsl_vector_set(x, 0, p[1]);
                   5968:     gsl_vector_set(x, 1, p[2]);
                   5969: 
                   5970:     minex_func.f = &gompertz_f;
                   5971:     minex_func.n = NDIM;
                   5972:     minex_func.params = (void *)&p; /* ??? */
                   5973:     
                   5974:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   5975:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   5976:     
                   5977:     printf("Iterations beginning .....\n\n");
                   5978:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   5979: 
                   5980:     iteri=0;
                   5981:     while (rval == GSL_CONTINUE){
                   5982:       iteri++;
                   5983:       status = gsl_multimin_fminimizer_iterate(sfm);
                   5984:       
                   5985:       if (status) printf("error: %s\n", gsl_strerror (status));
                   5986:       fflush(0);
                   5987:       
                   5988:       if (status) 
                   5989:         break;
                   5990:       
                   5991:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   5992:       ssval = gsl_multimin_fminimizer_size (sfm);
                   5993:       
                   5994:       if (rval == GSL_SUCCESS)
                   5995:         printf ("converged to a local maximum at\n");
                   5996:       
                   5997:       printf("%5d ", iteri);
                   5998:       for (it = 0; it < NDIM; it++){
                   5999:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   6000:       }
                   6001:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   6002:     }
                   6003:     
                   6004:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   6005:     
                   6006:     gsl_vector_free(x); /* initial values */
                   6007:     gsl_vector_free(ss); /* inital step size */
                   6008:     for (it=0; it<NDIM; it++){
                   6009:       p[it+1]=gsl_vector_get(sfm->x,it);
                   6010:       fprintf(ficrespow," %.12lf", p[it]);
                   6011:     }
                   6012:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   6013: #endif
                   6014: #ifdef POWELL
                   6015:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   6016: #endif  
1.126     brouard  6017:     fclose(ficrespow);
                   6018:     
                   6019:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
                   6020: 
                   6021:     for(i=1; i <=NDIM; i++)
                   6022:       for(j=i+1;j<=NDIM;j++)
                   6023:        matcov[i][j]=matcov[j][i];
                   6024:     
                   6025:     printf("\nCovariance matrix\n ");
                   6026:     for(i=1; i <=NDIM; i++) {
                   6027:       for(j=1;j<=NDIM;j++){ 
                   6028:        printf("%f ",matcov[i][j]);
                   6029:       }
                   6030:       printf("\n ");
                   6031:     }
                   6032:     
                   6033:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
                   6034:     for (i=1;i<=NDIM;i++) 
                   6035:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   6036: 
                   6037:     lsurv=vector(1,AGESUP);
                   6038:     lpop=vector(1,AGESUP);
                   6039:     tpop=vector(1,AGESUP);
                   6040:     lsurv[agegomp]=100000;
                   6041:     
                   6042:     for (k=agegomp;k<=AGESUP;k++) {
                   6043:       agemortsup=k;
                   6044:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   6045:     }
                   6046:     
                   6047:     for (k=agegomp;k<agemortsup;k++)
                   6048:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   6049:     
                   6050:     for (k=agegomp;k<agemortsup;k++){
                   6051:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   6052:       sumlpop=sumlpop+lpop[k];
                   6053:     }
                   6054:     
                   6055:     tpop[agegomp]=sumlpop;
                   6056:     for (k=agegomp;k<(agemortsup-3);k++){
                   6057:       /*  tpop[k+1]=2;*/
                   6058:       tpop[k+1]=tpop[k]-lpop[k];
                   6059:     }
                   6060:     
                   6061:     
                   6062:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   6063:     for (k=agegomp;k<(agemortsup-2);k++) 
                   6064:       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]);
                   6065:     
                   6066:     
                   6067:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   6068:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   6069:     
                   6070:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
                   6071:                     stepm, weightopt,\
                   6072:                     model,imx,p,matcov,agemortsup);
                   6073:     
                   6074:     free_vector(lsurv,1,AGESUP);
                   6075:     free_vector(lpop,1,AGESUP);
                   6076:     free_vector(tpop,1,AGESUP);
1.136     brouard  6077: #ifdef GSL
                   6078:     free_ivector(cens,1,n);
                   6079:     free_vector(agecens,1,n);
                   6080:     free_ivector(dcwave,1,n);
                   6081:     free_matrix(ximort,1,NDIM,1,NDIM);
                   6082: #endif
1.126     brouard  6083:   } /* Endof if mle==-3 */
                   6084:   
                   6085:   else{ /* For mle >=1 */
1.132     brouard  6086:     globpr=0;/* debug */
                   6087:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  6088:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   6089:     for (k=1; k<=npar;k++)
                   6090:       printf(" %d %8.5f",k,p[k]);
                   6091:     printf("\n");
                   6092:     globpr=1; /* to print the contributions */
                   6093:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   6094:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   6095:     for (k=1; k<=npar;k++)
                   6096:       printf(" %d %8.5f",k,p[k]);
                   6097:     printf("\n");
                   6098:     if(mle>=1){ /* Could be 1 or 2 */
                   6099:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   6100:     }
                   6101:     
                   6102:     /*--------- results files --------------*/
                   6103:     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);
                   6104:     
                   6105:     
                   6106:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6107:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6108:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6109:     for(i=1,jk=1; i <=nlstate; i++){
                   6110:       for(k=1; k <=(nlstate+ndeath); k++){
                   6111:        if (k != i) {
                   6112:          printf("%d%d ",i,k);
                   6113:          fprintf(ficlog,"%d%d ",i,k);
                   6114:          fprintf(ficres,"%1d%1d ",i,k);
                   6115:          for(j=1; j <=ncovmodel; j++){
                   6116:            printf("%lf ",p[jk]);
                   6117:            fprintf(ficlog,"%lf ",p[jk]);
                   6118:            fprintf(ficres,"%lf ",p[jk]);
                   6119:            jk++; 
                   6120:          }
                   6121:          printf("\n");
                   6122:          fprintf(ficlog,"\n");
                   6123:          fprintf(ficres,"\n");
                   6124:        }
                   6125:       }
                   6126:     }
                   6127:     if(mle!=0){
                   6128:       /* Computing hessian and covariance matrix */
                   6129:       ftolhess=ftol; /* Usually correct */
                   6130:       hesscov(matcov, p, npar, delti, ftolhess, func);
                   6131:     }
                   6132:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   6133:     printf("# Scales (for hessian or gradient estimation)\n");
                   6134:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   6135:     for(i=1,jk=1; i <=nlstate; i++){
                   6136:       for(j=1; j <=nlstate+ndeath; j++){
                   6137:        if (j!=i) {
                   6138:          fprintf(ficres,"%1d%1d",i,j);
                   6139:          printf("%1d%1d",i,j);
                   6140:          fprintf(ficlog,"%1d%1d",i,j);
                   6141:          for(k=1; k<=ncovmodel;k++){
                   6142:            printf(" %.5e",delti[jk]);
                   6143:            fprintf(ficlog," %.5e",delti[jk]);
                   6144:            fprintf(ficres," %.5e",delti[jk]);
                   6145:            jk++;
                   6146:          }
                   6147:          printf("\n");
                   6148:          fprintf(ficlog,"\n");
                   6149:          fprintf(ficres,"\n");
                   6150:        }
                   6151:       }
                   6152:     }
                   6153:     
                   6154:     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");
                   6155:     if(mle>=1)
                   6156:       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");
                   6157:     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");
                   6158:     /* # 121 Var(a12)\n\ */
                   6159:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6160:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   6161:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   6162:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   6163:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   6164:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   6165:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   6166:     
                   6167:     
                   6168:     /* Just to have a covariance matrix which will be more understandable
                   6169:        even is we still don't want to manage dictionary of variables
                   6170:     */
                   6171:     for(itimes=1;itimes<=2;itimes++){
                   6172:       jj=0;
                   6173:       for(i=1; i <=nlstate; i++){
                   6174:        for(j=1; j <=nlstate+ndeath; j++){
                   6175:          if(j==i) continue;
                   6176:          for(k=1; k<=ncovmodel;k++){
                   6177:            jj++;
                   6178:            ca[0]= k+'a'-1;ca[1]='\0';
                   6179:            if(itimes==1){
                   6180:              if(mle>=1)
                   6181:                printf("#%1d%1d%d",i,j,k);
                   6182:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   6183:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   6184:            }else{
                   6185:              if(mle>=1)
                   6186:                printf("%1d%1d%d",i,j,k);
                   6187:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   6188:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   6189:            }
                   6190:            ll=0;
                   6191:            for(li=1;li <=nlstate; li++){
                   6192:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   6193:                if(lj==li) continue;
                   6194:                for(lk=1;lk<=ncovmodel;lk++){
                   6195:                  ll++;
                   6196:                  if(ll<=jj){
                   6197:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   6198:                    if(ll<jj){
                   6199:                      if(itimes==1){
                   6200:                        if(mle>=1)
                   6201:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6202:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6203:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6204:                      }else{
                   6205:                        if(mle>=1)
                   6206:                          printf(" %.5e",matcov[jj][ll]); 
                   6207:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   6208:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   6209:                      }
                   6210:                    }else{
                   6211:                      if(itimes==1){
                   6212:                        if(mle>=1)
                   6213:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   6214:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   6215:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   6216:                      }else{
                   6217:                        if(mle>=1)
                   6218:                          printf(" %.5e",matcov[jj][ll]); 
                   6219:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   6220:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   6221:                      }
                   6222:                    }
                   6223:                  }
                   6224:                } /* end lk */
                   6225:              } /* end lj */
                   6226:            } /* end li */
                   6227:            if(mle>=1)
                   6228:              printf("\n");
                   6229:            fprintf(ficlog,"\n");
                   6230:            fprintf(ficres,"\n");
                   6231:            numlinepar++;
                   6232:          } /* end k*/
                   6233:        } /*end j */
                   6234:       } /* end i */
                   6235:     } /* end itimes */
                   6236:     
                   6237:     fflush(ficlog);
                   6238:     fflush(ficres);
                   6239:     
                   6240:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6241:       ungetc(c,ficpar);
                   6242:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6243:       fputs(line,stdout);
1.126     brouard  6244:       fputs(line,ficparo);
                   6245:     }
                   6246:     ungetc(c,ficpar);
                   6247:     
                   6248:     estepm=0;
                   6249:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   6250:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   6251:     if (fage <= 2) {
                   6252:       bage = ageminpar;
                   6253:       fage = agemaxpar;
                   6254:     }
                   6255:     
                   6256:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   6257:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   6258:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   6259:     
                   6260:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6261:       ungetc(c,ficpar);
                   6262:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6263:       fputs(line,stdout);
1.126     brouard  6264:       fputs(line,ficparo);
                   6265:     }
                   6266:     ungetc(c,ficpar);
                   6267:     
                   6268:     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);
                   6269:     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);
                   6270:     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);
                   6271:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   6272:     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);
                   6273:     
                   6274:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6275:       ungetc(c,ficpar);
                   6276:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6277:       fputs(line,stdout);
1.126     brouard  6278:       fputs(line,ficparo);
                   6279:     }
                   6280:     ungetc(c,ficpar);
                   6281:     
                   6282:     
                   6283:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   6284:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   6285:     
                   6286:     fscanf(ficpar,"pop_based=%d\n",&popbased);
                   6287:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   6288:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   6289:     
                   6290:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6291:       ungetc(c,ficpar);
                   6292:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6293:       fputs(line,stdout);
1.126     brouard  6294:       fputs(line,ficparo);
                   6295:     }
                   6296:     ungetc(c,ficpar);
                   6297:     
                   6298:     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);
                   6299:     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);
                   6300:     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);
                   6301:     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);
                   6302:     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);
                   6303:     /* day and month of proj2 are not used but only year anproj2.*/
                   6304:     
                   6305:     
                   6306:     
1.145     brouard  6307:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   6308:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  6309:     
                   6310:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   6311:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   6312:     
                   6313:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                   6314:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   6315:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   6316:       
                   6317:    /*------------ free_vector  -------------*/
                   6318:    /*  chdir(path); */
                   6319:  
                   6320:     free_ivector(wav,1,imx);
                   6321:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   6322:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   6323:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   6324:     free_lvector(num,1,n);
                   6325:     free_vector(agedc,1,n);
                   6326:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   6327:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   6328:     fclose(ficparo);
                   6329:     fclose(ficres);
                   6330: 
                   6331: 
                   6332:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.145     brouard  6333: #include "prevlim.h"  /* Use ficrespl, ficlog */
1.126     brouard  6334:     fclose(ficrespl);
                   6335: 
1.145     brouard  6336: #ifdef FREEEXIT2
                   6337: #include "freeexit2.h"
                   6338: #endif
                   6339: 
1.126     brouard  6340:     /*------------- h Pij x at various ages ------------*/
1.145     brouard  6341: #include "hpijx.h"
                   6342:     fclose(ficrespij);
1.126     brouard  6343: 
1.145     brouard  6344:   /*-------------- Variance of one-step probabilities---*/
                   6345:     k=1;
1.126     brouard  6346:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   6347: 
                   6348: 
                   6349:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6350:     for(i=1;i<=AGESUP;i++)
                   6351:       for(j=1;j<=NCOVMAX;j++)
                   6352:        for(k=1;k<=NCOVMAX;k++)
                   6353:          probs[i][j][k]=0.;
                   6354: 
                   6355:     /*---------- Forecasting ------------------*/
                   6356:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   6357:     if(prevfcast==1){
                   6358:       /*    if(stepm ==1){*/
                   6359:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
                   6360:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   6361:       /*      }  */
                   6362:       /*      else{ */
                   6363:       /*        erreur=108; */
                   6364:       /*        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); */
                   6365:       /*        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); */
                   6366:       /*      } */
                   6367:     }
                   6368:   
                   6369: 
1.127     brouard  6370:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   6371: 
                   6372:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   6373:     /*  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",\
                   6374:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   6375:     */
1.126     brouard  6376: 
1.127     brouard  6377:     if (mobilav!=0) {
                   6378:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6379:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   6380:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   6381:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   6382:       }
1.126     brouard  6383:     }
                   6384: 
                   6385: 
1.127     brouard  6386:     /*---------- Health expectancies, no variances ------------*/
                   6387: 
1.126     brouard  6388:     strcpy(filerese,"e");
                   6389:     strcat(filerese,fileres);
                   6390:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   6391:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   6392:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   6393:     }
                   6394:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   6395:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  6396:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6397:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   6398:           
                   6399:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  6400:        fprintf(ficreseij,"\n#****** ");
                   6401:        for(j=1;j<=cptcoveff;j++) {
                   6402:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6403:        }
                   6404:        fprintf(ficreseij,"******\n");
                   6405: 
                   6406:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6407:        oldm=oldms;savm=savms;
                   6408:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   6409:       
                   6410:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  6411:       /*}*/
1.127     brouard  6412:     }
                   6413:     fclose(ficreseij);
                   6414: 
                   6415: 
                   6416:     /*---------- Health expectancies and variances ------------*/
                   6417: 
                   6418: 
                   6419:     strcpy(filerest,"t");
                   6420:     strcat(filerest,fileres);
                   6421:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   6422:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   6423:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   6424:     }
                   6425:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   6426:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   6427: 
1.126     brouard  6428: 
                   6429:     strcpy(fileresstde,"stde");
                   6430:     strcat(fileresstde,fileres);
                   6431:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   6432:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   6433:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   6434:     }
                   6435:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   6436:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   6437: 
                   6438:     strcpy(filerescve,"cve");
                   6439:     strcat(filerescve,fileres);
                   6440:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   6441:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   6442:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   6443:     }
                   6444:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   6445:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   6446: 
                   6447:     strcpy(fileresv,"v");
                   6448:     strcat(fileresv,fileres);
                   6449:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   6450:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   6451:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   6452:     }
                   6453:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   6454:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   6455: 
1.145     brouard  6456:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6457:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   6458:           
                   6459:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6460:        fprintf(ficrest,"\n#****** ");
1.126     brouard  6461:        for(j=1;j<=cptcoveff;j++) 
                   6462:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6463:        fprintf(ficrest,"******\n");
                   6464: 
                   6465:        fprintf(ficresstdeij,"\n#****** ");
                   6466:        fprintf(ficrescveij,"\n#****** ");
                   6467:        for(j=1;j<=cptcoveff;j++) {
                   6468:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6469:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6470:        }
                   6471:        fprintf(ficresstdeij,"******\n");
                   6472:        fprintf(ficrescveij,"******\n");
                   6473: 
                   6474:        fprintf(ficresvij,"\n#****** ");
                   6475:        for(j=1;j<=cptcoveff;j++) 
                   6476:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6477:        fprintf(ficresvij,"******\n");
                   6478: 
                   6479:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6480:        oldm=oldms;savm=savms;
1.127     brouard  6481:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  6482:        /*
                   6483:         */
                   6484:        /* goto endfree; */
1.126     brouard  6485:  
                   6486:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6487:        pstamp(ficrest);
1.145     brouard  6488: 
                   6489: 
1.128     brouard  6490:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145     brouard  6491:          oldm=oldms;savm=savms; /* Segmentation fault */
                   6492:          varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart);
                   6493:          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 ");
1.128     brouard  6494:          if(vpopbased==1)
                   6495:            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);
                   6496:          else
                   6497:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   6498:          fprintf(ficrest,"# Age e.. (std) ");
                   6499:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   6500:          fprintf(ficrest,"\n");
1.126     brouard  6501: 
1.128     brouard  6502:          epj=vector(1,nlstate+1);
                   6503:          for(age=bage; age <=fage ;age++){
                   6504:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   6505:            if (vpopbased==1) {
                   6506:              if(mobilav ==0){
                   6507:                for(i=1; i<=nlstate;i++)
                   6508:                  prlim[i][i]=probs[(int)age][i][k];
                   6509:              }else{ /* mobilav */ 
                   6510:                for(i=1; i<=nlstate;i++)
                   6511:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   6512:              }
1.126     brouard  6513:            }
                   6514:        
1.128     brouard  6515:            fprintf(ficrest," %4.0f",age);
                   6516:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   6517:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   6518:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   6519:                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   6520:              }
                   6521:              epj[nlstate+1] +=epj[j];
1.126     brouard  6522:            }
                   6523: 
1.128     brouard  6524:            for(i=1, vepp=0.;i <=nlstate;i++)
                   6525:              for(j=1;j <=nlstate;j++)
                   6526:                vepp += vareij[i][j][(int)age];
                   6527:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   6528:            for(j=1;j <=nlstate;j++){
                   6529:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   6530:            }
                   6531:            fprintf(ficrest,"\n");
1.126     brouard  6532:          }
                   6533:        }
                   6534:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   6535:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   6536:        free_vector(epj,1,nlstate+1);
1.145     brouard  6537:       /*}*/
1.126     brouard  6538:     }
                   6539:     free_vector(weight,1,n);
1.145     brouard  6540:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  6541:     free_imatrix(s,1,maxwav+1,1,n);
                   6542:     free_matrix(anint,1,maxwav,1,n); 
                   6543:     free_matrix(mint,1,maxwav,1,n);
                   6544:     free_ivector(cod,1,n);
                   6545:     free_ivector(tab,1,NCOVMAX);
                   6546:     fclose(ficresstdeij);
                   6547:     fclose(ficrescveij);
                   6548:     fclose(ficresvij);
                   6549:     fclose(ficrest);
                   6550:     fclose(ficpar);
                   6551:   
                   6552:     /*------- Variance of period (stable) prevalence------*/   
                   6553: 
                   6554:     strcpy(fileresvpl,"vpl");
                   6555:     strcat(fileresvpl,fileres);
                   6556:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   6557:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   6558:       exit(0);
                   6559:     }
                   6560:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   6561: 
1.145     brouard  6562:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6563:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   6564:           
                   6565:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6566:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  6567:        for(j=1;j<=cptcoveff;j++) 
                   6568:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6569:        fprintf(ficresvpl,"******\n");
                   6570:       
                   6571:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   6572:        oldm=oldms;savm=savms;
                   6573:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
                   6574:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  6575:       /*}*/
1.126     brouard  6576:     }
                   6577: 
                   6578:     fclose(ficresvpl);
                   6579: 
                   6580:     /*---------- End : free ----------------*/
                   6581:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6582:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6583:   }  /* mle==-3 arrives here for freeing */
1.131     brouard  6584:  endfree:
1.141     brouard  6585:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  6586:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   6587:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6588:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6589:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6590:     free_matrix(covar,0,NCOVMAX,1,n);
                   6591:     free_matrix(matcov,1,npar,1,npar);
                   6592:     /*free_vector(delti,1,npar);*/
                   6593:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6594:     free_matrix(agev,1,maxwav,1,imx);
                   6595:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   6596: 
1.145     brouard  6597:     free_ivector(ncodemax,1,NCOVMAX);
                   6598:     free_ivector(Tvar,1,NCOVMAX);
                   6599:     free_ivector(Tprod,1,NCOVMAX);
                   6600:     free_ivector(Tvaraff,1,NCOVMAX);
                   6601:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  6602: 
                   6603:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   6604:     free_imatrix(codtab,1,100,1,10);
                   6605:   fflush(fichtm);
                   6606:   fflush(ficgp);
                   6607:   
                   6608: 
                   6609:   if((nberr >0) || (nbwarn>0)){
                   6610:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   6611:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   6612:   }else{
                   6613:     printf("End of Imach\n");
                   6614:     fprintf(ficlog,"End of Imach\n");
                   6615:   }
                   6616:   printf("See log file on %s\n",filelog);
                   6617:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
                   6618:   (void) gettimeofday(&end_time,&tzp);
                   6619:   tm = *localtime(&end_time.tv_sec);
                   6620:   tmg = *gmtime(&end_time.tv_sec);
                   6621:   strcpy(strtend,asctime(&tm));
                   6622:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   6623:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
                   6624:   printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
                   6625: 
1.141     brouard  6626:   printf("Total time was %ld Sec.\n", end_time.tv_sec -start_time.tv_sec);
1.126     brouard  6627:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
1.141     brouard  6628:   fprintf(ficlog,"Total time was %ld Sec.\n", end_time.tv_sec -start_time.tv_sec);
1.126     brouard  6629:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   6630: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   6631:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   6632:   fclose(fichtm);
                   6633:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   6634:   fclose(fichtmcov);
                   6635:   fclose(ficgp);
                   6636:   fclose(ficlog);
                   6637:   /*------ End -----------*/
                   6638: 
                   6639: 
                   6640:    printf("Before Current directory %s!\n",pathcd);
                   6641:    if(chdir(pathcd) != 0)
                   6642:     printf("Can't move to directory %s!\n",path);
                   6643:   if(getcwd(pathcd,MAXLINE) > 0)
                   6644:     printf("Current directory %s!\n",pathcd);
                   6645:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   6646:   sprintf(plotcmd,"gnuplot");
                   6647: #ifndef UNIX
                   6648:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   6649: #endif
                   6650:   if(!stat(plotcmd,&info)){
                   6651:     printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
                   6652:     if(!stat(getenv("GNUPLOTBIN"),&info)){
                   6653:       printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
                   6654:     }else
                   6655:       strcpy(pplotcmd,plotcmd);
                   6656: #ifdef UNIX
                   6657:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   6658:     if(!stat(plotcmd,&info)){
                   6659:       printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
                   6660:     }else
                   6661:       strcpy(pplotcmd,plotcmd);
                   6662: #endif
                   6663:   }else
                   6664:     strcpy(pplotcmd,plotcmd);
                   6665:   
                   6666:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
                   6667:   printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);
                   6668: 
                   6669:   if((outcmd=system(plotcmd)) != 0){
1.151   ! brouard  6670:     printf("\n Problem with gnuplot command %s\n", plotcmd);
1.150     brouard  6671:     printf("\n Trying on same directory\n");
                   6672:     sprintf(plotcmd,"./gnuplot %s", optionfilegnuplot);
                   6673:     if((outcmd=system(plotcmd)) != 0)
                   6674:       printf("\n Still a problem with gnuplot command %s\n", plotcmd);
1.126     brouard  6675:   }
                   6676:   printf(" Wait...");
                   6677:   while (z[0] != 'q') {
                   6678:     /* chdir(path); */
                   6679:     printf("\nType e to edit output files, g to graph again and q for exiting: ");
                   6680:     scanf("%s",z);
                   6681: /*     if (z[0] == 'c') system("./imach"); */
                   6682:     if (z[0] == 'e') {
                   6683:       printf("Starting browser with: %s",optionfilehtm);fflush(stdout);
                   6684:       system(optionfilehtm);
                   6685:     }
                   6686:     else if (z[0] == 'g') system(plotcmd);
                   6687:     else if (z[0] == 'q') exit(0);
                   6688:   }
                   6689:   end:
                   6690:   while (z[0] != 'q') {
                   6691:     printf("\nType  q for exiting: ");
                   6692:     scanf("%s",z);
                   6693:   }
                   6694: }
                   6695: 
                   6696: 
                   6697: 

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