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

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

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