File:  [Local Repository] / imach / src / imach.c
Revision 1.105: download - view: text, annotated - select for diffs
Thu Jan 5 20:23:19 2006 UTC (18 years, 5 months ago) by lievre
Branches: MAIN
CVS tags: HEAD
*** empty log message ***

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

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