/*
 *	File: lnreCarr.c
 *
 *      (C) IWTS
 *          KU Nijmegen
 *          The Netherlands
 *
 *      Author: R. Harald Baayen
 *		Stephen Tweedie
 *
 *      History:
 *
 *      - feb 1997, version 1.0 (rhb)
 *	- nov 1998, version 1.1 (rhb, st)
 *      - april 1999, version 1.2 (rhb)
 *            -e option added (mse in simplex minimization as score function)
 *
 *
 *      Description:
 *
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <malloc.h>
#include <math.h>
#include "lex_cons.h"


/* EXTERN FUNCTIONS */

/* functions for numerical procedures */

extern double	qromb ();
extern double	factln ();
extern double	gammln ();
extern int	find ();
extern double	findoptimalp ();
extern double	getmse ();
extern void	amoeba ();

extern double	sim_functie ();
extern double	sim_functie_mse ();
extern void	print_sim_matrix ();

extern double	*vector ();
extern double	**matrix ();
extern void	free_vector ();
extern void	free_matrix ();

/* functions for lognormal model */

extern double	expV ();
extern double	expV1 ();
extern double	expVm ();

extern double	funcVNy ();
extern double	funcV1Ny (); 
extern double	funcVmNy ();

/* argument reading, file manipulation, and help function */

extern int	leesgetal ();
extern void	change_extension ();
extern void	help ();


/* GLOBAL VARIABLES */

double   N, V, n1, n2,             /* number of tokens, types, hapaxes, disleg */
         E,                        /* extrapolation sample size */
         mmax,                     /* highest frequency rank */
         mrank,                    /* word frequency, used in expVm() */
         SPECTRUM[MAXM3][3],       /* frequency spectrum m Vm EVm */
         PVM[MAXM3],               /* m*Vm/N */
         mean, stdev, Z,           /* parameters */
         smean, sstdev, sZ,        /* sample-based estimates of parameters */
         Nzero, Vzero,             /* original sample size N0 */
         eV, eV2N, S, eV1, eV2,    /* E[V(N)], E[V(2N)], S, E[V(1,N)] */
         CHUNKS[MAXCHUNKS3],       /* the chunk sizes */
         chunksize, reMainder,     /* chunk variables */
         x, y, x1, y2, y3, y4, y5,
         gN, gm,                   /* N, m used by integration functions */
         t,
         **sim_mat,                /* for simplex minimization */
         *sim_vec,
         *sim_yy,
         miny,
         tolerance;

FILE     *fpspectrum,              /* fpspectrum: datafile: m, Vm */
         *fpexpspect,              /* expected spectrum */
         *fpexpspect2N,            /* spectrum at 2N */
         *fpVN,                    /* file with E[V(N)] and E[V(2N)] */
         *fpsum,                   /* file with summary of model */
         *fpint,                   /* interpolation results */
         *fpext,                   /* extrapolation results */
         *fpE,                     /* spectrum at sample size E */
 	 *fullspc,		   /* spectrum with m EVM for m=1..skip */
         *fpKvalues;               /* list N_k for k = 1..K, K+1,..,2K */

int      nranks,                   /* number of different ranks in spectrum */
         maxrank,                  /* largest rank for fit, default 15 */
         i, j, ii, 
         skip,                     /* don't bother about chi2 preparation */
         header,                   /* boolean for presence of header */
         k,                        /* variable for chunks */
         nchunks,                  /* number of chunks for interpolation */
         enchunks,                 /* number of chunks for extrapolation */
         token, type,              /* auxiliary variables for scanf */
         ndimensions,              /* for amoeba: simplex minimization */
         ndimensions1,             /* for amoeba: simplex minimization */
         niterations,              /* for amoeba: simplex minimization */
         simplex_flunked,          /* boolean for success of simplex */
         kfile,                    /* print fpKvalue file */
         again,                    /* boolean for manual param.estimation */
         forceN,                   /* force reading N and V from stdin */
         forceV,                   /* force reading N and V from stdin */
         freemem,                  /* free allocated memory */
         msemethod,                     /* use mse over msenranks ranks for
                                           parameter estimation */
         msenranks,                     /* number of ranks for mse param.
                                           estimation */
         aantal;                   /* for command line options */

char     woord[MAXWORDLENGTH],     /* variable for skipping header in fscanf */
         new_name[MAXWORDLENGTH],  /* variables for extension handling    */
         base_name[MAXWORDLENGTH],
         c,
         *fs;                      /* variable for scanning options */


/* MAIN () */

int main (argc, argv)
int     argc;
char    *argv[];

{
   /* DEFAULTS */

   maxrank = DEF_MAXRANK;
   nchunks = DEF_CHUNKS;
   enchunks = DEF_CHUNKS;
   header = 1;
   E = NULL_F;
   simplex_flunked = 0;
   skip = 0;
   kfile = 0;
   forceN = 0;
   freemem = 0;
   forceV = 0;   
   msenranks = maxrank;
   msemethod = 0;



   /* COMMAND LINE OPTIONS */

   while ((--argc > 0) && ((*++argv)[0] == '-')) {
        for (fs = argv[0] + 1; *fs != '\0'; fs++) {
            switch (*fs) {
            case 'h':
                help();
                break;
            case 'E':
                i =  leesgetal (fs, &aantal);
                E = (double) i;
                for (; aantal > 0; aantal--){
                   fs++;
                }
                break;
            case 'k':
                nchunks = leesgetal (fs, &aantal);
                for (; aantal > 0; aantal--){
                   fs++;
                }
                break;
            case 'K':
                enchunks = leesgetal (fs, &aantal);
                for (; aantal > 0; aantal--){
                   fs++;
                }
                break;
            case 'e':
                msenranks = leesgetal (fs, &aantal);
                msemethod = 1;
                for (; aantal > 0; aantal--){
                   fs++;
                }
                break;
            case 'V':
                forceV = leesgetal (fs, &aantal);
                for (; aantal > 0; aantal--){
                   fs++;
                }
                break;
            case 'N':
                forceN = leesgetal (fs, &aantal);
                for (; aantal > 0; aantal--){
                   fs++;
                }
                break;
            case 'm':
                maxrank = leesgetal (fs, &aantal);
                for (; aantal > 0; aantal--){
                   fs++;
                }
                break;
            case 'H':      /* input files without headers! */
                header = 0;
                break;
            case 'F':
                kfile = leesgetal (fs, &aantal);
                for (; aantal > 0; aantal--){
                   fs++;
                }
                if (kfile == 0) {
                  fprintf(stderr, "lnreCarr: cannot int/ext with zero N\n");
                  exit(1);
                }
                break;
            case 's':      /* don't interpolate or extrapolate */
                           /* show m and Vm and EVm for m=1..s */
                skip = leesgetal (fs, &aantal);
                for (; aantal > 0; aantal--){
                   fs++;
                }
                if (skip==0) {
                   fprintf(stderr, "lnreCarr: cannot skip with zero rank\n");
                   exit(1);
                }
                break;
            default:
                fprintf(stderr, "lnreCarr: illegal option %c\n", *fs);
                exit(1);
                break;
            }
        }
   } /* of while */

   /* FILE HANDLING */

   if (argc == 0) {
     help ();
   }

   /* load input spectrum, should have .spc extension */

   if ((fpspectrum = fopen(*argv, "r")) == NULL) {
       fprintf(stderr, "lnreCarr: can't open %s\n", *argv);
       exit(1);
   }

   /* file name handling output files */

   strncpy(base_name, *argv, strlen(*argv) - 4);

  if ((skip == 0) && (kfile == 0)) {
    change_extension (base_name, new_name, "_C.spc");
    if ((fpexpspect = fopen(new_name, "w")) == NULL){
      fprintf(stderr, "lnreCarr: can't open output file %s\n", new_name);
      exit(1);
    }
    change_extension (base_name, new_name, "_C.sp2");
    if ((fpexpspect2N = fopen(new_name, "w")) == NULL){
      fprintf(stderr, "lnreCarr: can't open output file %s\n", new_name);
      exit(1);
    }
    change_extension (base_name, new_name, "_C.ev2");
    if ((fpVN = fopen(new_name, "w")) == NULL){
      fprintf(stderr, "lnreCarr: can't open output file %s\n", new_name);
      exit(1);
    }
    change_extension (base_name, new_name, "_C.sum");
    if ((fpsum = fopen(new_name, "w")) == NULL){
      fprintf(stderr, "lnreCarr: can't open output file %s\n", new_name);
      exit(1);
    }
    change_extension (base_name, new_name, "_C.int");
    if ((fpint = fopen(new_name, "w")) == NULL){
      fprintf(stderr, "lnreCarr: can't open output file %s\n", new_name);
      exit(1);
    }
    change_extension (base_name, new_name, "_C.ext");
    if ((fpext = fopen(new_name, "w")) == NULL){
      fprintf(stderr, "lnreCarr: can't open output file %s\n", new_name);
      exit(1);
    }
    if (E > NULL_F){
     change_extension (base_name, new_name, "_C.sp3");
     if ((fpE = fopen(new_name, "w")) == NULL){
        fprintf(stderr, "lnreCarr: can't open output file %s\n", new_name);
        exit(1);
     }
    }
   } else {
     if (skip > 0) {
        change_extension (base_name, new_name, "_C.fsp");
        if ((fullspc = fopen(new_name, "w")) == NULL){
           fprintf(stderr, "lnreCarr: can't open output file %s\n", new_name);
           exit(1);
        }
	/* CHANGE HERE - THIS BIT ADDED */
        change_extension (base_name, new_name, "_C.sum");
        if ((fpsum = fopen(new_name, "w")) == NULL){
          fprintf(stderr, "lnreCarr: can't open output file %s\n", new_name);
          exit(1);
        }
     } else {
        change_extension (base_name, new_name, "_C.iex");
        if ((fpKvalues = fopen(new_name, "w")) == NULL){
           fprintf(stderr, "lnreCarr: can't open output file %s\n", new_name);
           exit(1);
        }
     }
   }

   fprintf(stdout, "LNRE analysis with Carroll's LogNormal Model\n");
   fflush(stdout);

   /* LOAD SPECTRUM FILE */

   nranks = 0; n1 = 0; n2 = 0; mean = NULL_F; stdev = NULL_F;
   if (header){
      fscanf(fpspectrum, "%s ", woord);  /* m */
      fscanf(fpspectrum, "%s ", woord);  /* Vm */
   }

   while (fscanf(fpspectrum, "%d %d", &token, &type) != EOF)  {
        nranks++;
        SPECTRUM[nranks][0] = (double) token;
        SPECTRUM[nranks][1] = (double) type;
        if (token == 1) n1 = type;
        if (token == 2) n2 = type;
        N+= (double) token * (double) type;
        V+= (double) type;
   }
   mmax = SPECTRUM[nranks][0];
   Nzero = N; Vzero = V;

   if (forceN > 0) {
       Nzero = (double) forceN;
       N = (double) forceN;
   }
   if (forceV > 0){
       Vzero = (double) forceV;
       V = (double) forceV;
   }

   /* CALCULATE SAMPLE MEAN AND VARIANCE */
   /*  cancelled, this never gives a good estimate */
   /*
   if ((forceN == 0 ) && (forceV == 0 ) ) {
     smean = NULL_F;
     for (i = 1; i <= nranks; i++){
        PVM[i] = log(SPECTRUM[i][1] * SPECTRUM[i][0]/Nzero);
        smean += PVM[i];
     }
     smean = smean/((double) nranks);
     sZ = exp(-smean); 
     sstdev = NULL_F;
     for (i = 1; i <= nranks; i++){
          sstdev += (PVM[i] - smean)*(PVM[i] - smean);
     }
     sstdev = sqrt(sstdev/((double)(nranks-1)));

     Z = sZ; stdev = sstdev;
     eV = expV(N);
     eV1 = expV1(N);
     eV2 = expVm(N, 2.0);
   }
   */

   Z = 200.0;
   stdev = 1.5;
   eV = expV(N);
   eV1 = expV1(N);
   eV2 = expVm(N, 2.0);

   /* PARAMETER ESTIMATION */

   fprintf(stdout, "starting parameter estimation\n");
   fflush(stdout);

   ndimensions = 2;  /* specific for lognormal model */
   ndimensions1 = ndimensions+1;
   tolerance = 0.01;
   niterations = 0;


   fprintf(stdout, "run downhill simplex minimization? (y/n) \n");
   scanf("%1s", &c);
   if (c=='y'){
    fprintf(stdout, "Initial values for minimization (sample values):\n");
    fprintf(stdout, "   Z  = %10.4f,  stdev  = %10.2f\n", Z, stdev);
    fprintf(stdout, "   V  = %15.0f,  E[V]   = %15.2f\n", V, eV);
    fprintf(stdout, "   V1 = %15.0f,  E[V1]  = %15.2f\n", n1, eV1);
    fprintf(stdout, "   V2 = %15.0f,  E[V2]  = %15.2f\n", n2, eV2);
    fprintf(stdout, "proceed (y), specify own starting point (o), or quit (q) ");
    scanf("%1s", &c);
    if (c=='q'){
       exit(1);
    }
    if (c=='o'){
     fprintf(stdout, "specify Z and stdev: ");
     scanf("%lf %lf", &Z, &stdev);
    }
    fprintf(stdout, "tolerance = %f, change? (y/n) ", tolerance);
    scanf("%1s", &c);
    if (c=='y') {
        fprintf(stdout, "specify tolerance: ");
        scanf("%lf", &tolerance);
    }
    fprintf(stdout, "\nStarting simplex method for parameter estimation\n");
    fflush(stdout);

    sim_mat = matrix (1, ndimensions + 1, 1, ndimensions);
    freemem = 1;
    sim_mat[1][1] = Z; sim_mat[1][2] = stdev;
    sim_mat[2][1] = 0.7*Z; sim_mat[2][2] = stdev-(0.2*stdev);
    sim_mat[3][1] = 1.7*Z; sim_mat[3][2] = stdev+(0.2*stdev);

    sim_vec = vector (1, ndimensions + 1);
    sim_yy = vector (1, ndimensions);

    for (i = 1; i <= ndimensions+1; i++){
      sim_yy[1] = sim_mat[i][1];
      sim_yy[2] = sim_mat[i][2];
      /* sim_vec[i] = sim_functie(sim_yy); */
      if (msemethod == 0) {
            sim_vec[i] = sim_functie(sim_yy);
      } else {
            sim_vec[i] = sim_functie_mse(sim_yy);
      }
    }

    /*
    amoeba (sim_mat,sim_vec,ndimensions,tolerance,sim_functie,&niterations,0);
    */
    if (msemethod == 0) {
         amoeba (sim_mat, sim_vec, ndimensions, tolerance, sim_functie, \
               &niterations,0);
    } else {
         amoeba (sim_mat, sim_vec, ndimensions, tolerance, sim_functie_mse, \
               &niterations,0);
    }

    fprintf(stdout, "\n");  /* ends report of simplex procedure */
    fflush(stdout);

    /* print_sim_matrix(sim_mat,ndimensions); */

    /* find minimum for which values are less than tolerance */
    miny = MAXX;
    for (i = 1; i <= ndimensions + 1; i++){
      if (sim_vec[i] < miny){
        j = i;
        miny = sim_vec[i];
      }
    }

    Z = sim_mat[j][1];
    stdev = sim_mat[j][2];
   }
   else {
     simplex_flunked = 1;
   }

   if (simplex_flunked){   /* TRY MANUALLY */
     fprintf(stdout, "sample estimates: mean = %f, stdev = %f, Z = %f\n",
           smean, sstdev, sZ);

     fflush(stdout);
     again = 1;
     while (again){
      fprintf(stdout, "specify Z, stdev\n ");
      scanf("%lf %lf", &Z, &stdev);
      eV = expV(N);
      eV1 = expV1(N);
      fprintf(stdout, "Starting summary of manually chosen parameters and results\n");
      fprintf(stdout, "V       =    %10.2f   V1      =   %10.2f\n", V, n1);
      fprintf(stdout, "E[V]    =    %10.2f   E[V1]   =   %10.2f\n", eV, eV1);
      fprintf(stdout, "Z  = %20.10f stdev = %20.10f\n", Z, stdev);
      fprintf(stdout, "reestimate (r), continue (c) or quit (q)? ");
      scanf("%s", &c);
      if (c=='q') {
           exit(1);   
      }
      else{
          if (c=='r') again=1;
          else again = 0;
      }
     }
     fflush(stdout);
   }

   /* NOW CALCULATE E[V(N)] AND E[V(m,N)]  */

   eV = expV(N);
   SPECTRUM[1][2] = eV1;
   /*
   fprintf(stderr, "EV = %10.4f EV1 = %10.4f  MSE = %10.4f\n",\
         eV, eV1, getmse());
   */
   mean = -log(Z);
   S = exp((0.5*stdev*stdev) - mean);

   if (skip>0) {
    fprintf(stdout, "\ncomputing EVm for m=1..%d\n", skip);
    fprintf(stdout, "Z = %20.10f stdev = %20.10f\n", Z, stdev);
    fflush(stdout);
    fprintf(fullspc, "m EVm\n");
    fprintf(fullspc, "%10d %30.20f\n", 1, eV1);
    fprintf(stdout, "[1]\n"); fflush(stdout);
    for (i = 2; i <= skip; i++) {
      fprintf(fullspc, "%10d %30.20f\n", i, expVm(N, (double) i) );
      fprintf(stdout, "[%d]\n", i); fflush(stdout);
    }
    fprintf(stdout, "E[V] = %15.2f   S         = %12.5f\n", eV, S);
    fflush(stdout);
    fclose(fullspc);

    fprintf(fpsum, "The lognormal model for %s", *argv);
    if (msemethod == 0) {
     fprintf(fpsum, " (parameter estimation using E[V(N)] and E[V(1,N)])\n");
    } else {
     fprintf(fpsum, " (parameter estimation using mse method with %d ranks)\n",\
                msenranks);
    }
    fprintf(fpsum, "N         = %12d\n", (int) N);
    fprintf(fpsum, "V(N)      = %12d\n", (int) V);
    fprintf(fpsum, "E[V(N)]   = %12.4f\n", eV);
    fprintf(fpsum, "V(1,N)    = %12d\n", (int) n1);
    fprintf(fpsum, "E[V(1,N)] = %12.4f\n", SPECTRUM[1][2]);
    fprintf(fpsum, "V(2,N)    = %12d\n", (int) SPECTRUM[2][1]);
    fprintf(fpsum, "E[V(2,N)] = %12.4f\n", SPECTRUM[2][2]);
    fprintf(fpsum, "S         = %12.1f\n", S);
    fprintf(fpsum, "Z         = %15.10f\n",  Z);
    fprintf(fpsum, "mean      = %15.10f\n",  mean);
    fprintf(fpsum, "stdev     = %15.10f\n",  stdev);
    fclose(fpsum);
    fprintf(stdout, "MSE(%d+2) = %10.4f\n", msenranks, getmse());
    exit(1);
   }
   fprintf(stdout, "MSE(%d+2) = %10.4f\n", msenranks, getmse());

   if (kfile > 0) {
     Nzero = (double) kfile;
     chunksize = floor(Nzero/(nchunks*1.0));
     reMainder = Nzero - ((nchunks*1.0) * chunksize);
     for (k = 1; k <= nchunks; k++)   CHUNKS[k] = chunksize;
     for (k = 1; k <= reMainder; k++) CHUNKS[k]++;
     for (k = 2; k <= nchunks; k++)   CHUNKS[k] += CHUNKS[k-1];

     fprintf(stdout, "computing interpolation+extrapolation statistics\n");
     fflush(stdout);

     fprintf(fpKvalues, "       N       EV      EV1      EV2      EV3      EV4      EV5       GV\n");
     for (k = 1; k <= nchunks; k++){
        fprintf(stdout, "[%d]\n", k);
        fflush(stdout);
        x = expV(CHUNKS[k]);
        x1 = expV(CHUNKS[k]+1.0);
        y = expVm(CHUNKS[k], 1.0);
        y2 = expVm(CHUNKS[k], 2.0);
        y3 = expVm(CHUNKS[k], 3.0);
        y4 = expVm(CHUNKS[k], 4.0);
        y5 = expVm(CHUNKS[k], 5.0);
        fprintf(fpKvalues, "%15.2f %15.2f %15.2f %15.2f %15.2f %15.2f %15.2f %15.4f\n", CHUNKS[k], x, y, y2, y3, y4, y5, x1-x);
     }
     fprintf(stdout, "\n");
     fflush(stdout);
     exit(1);
   }

   fprintf(stdout, "\ncomputing expected spectrum at N\n");
   fprintf(stdout, "[1]\n");
   fflush(stdout);
   SPECTRUM[1][2]=eV1;  /* eV1 is set in getmse() */
   for (i = 2; i <= maxrank; i++) {
     fprintf(stdout, "[%d]\n", i);
     fflush(stdout);
     SPECTRUM[i][2] = expVm(N, SPECTRUM[i][0]);
   }
   fprintf(stdout, "\n");
   fflush(stdout);

   /* PRINT SUMMARY */
   /* WARNING: ANY CHANGES HERE SHOULD BE IMMEDIATELY UPDATED IN ad2Carr */

   fprintf(fpsum, "The lognormal model for %s", *argv);
   if (msemethod == 0) {
     fprintf(fpsum, " (parameter estimation using E[V(N)] and E[V(1,N)])\n");
   } else {
     fprintf(fpsum, " (parameter estimation using mse method with %d ranks)\n",\
                msenranks);
   }
   fprintf(fpsum, "N         = %12d\n", (int) N);
   fprintf(fpsum, "V(N)      = %12d\n", (int) V);
   fprintf(fpsum, "E[V(N)]   = %12.4f\n", eV);
   fprintf(fpsum, "V(1,N)    = %12d\n", (int) n1);
   fprintf(fpsum, "E[V(1,N)] = %12.4f\n", SPECTRUM[1][2]);
   fprintf(fpsum, "V(2,N)    = %12d\n", (int) n2);
   fprintf(fpsum, "E[V(2,N)] = %12.4f\n", SPECTRUM[2][2]);
   fprintf(fpsum, "S         = %12.1f\n", S);
   fprintf(fpsum, "Z         = %15.10f\n",  Z);
   fprintf(fpsum, "mean      = %15.10f\n",  mean);
   fprintf(fpsum, "stdev     = %15.10f\n",  stdev);
   /* fprintf(fpsum, "MSE(%d+2) = %10.4f\n", msenranks, getmse()); */
   fclose(fpsum);
   fprintf(stdout, "MSE(%d+2) = %10.4f\n", msenranks, getmse());

   /* PRINT SPECTRUM */

   fprintf(fpexpspect, "         m         Vm        EVm     alphaM    EalphaM\n");
   for (i = 1; i <= maxrank; i++) {
    fprintf(fpexpspect, "%10d %10d ",(int) SPECTRUM[i][0],(int) SPECTRUM[i][1]);
    fprintf(fpexpspect, "%15.4f %15.4f %15.4f\n", SPECTRUM[i][2],
           SPECTRUM[i][1]/Vzero, SPECTRUM[i][2]/eV);
   }
   fclose(fpexpspect);

   /* PRINT SPECTRUM AT 2N */

   fprintf(stdout, "computing expected spectrum at 2N\n");
   fflush(stdout);
   N = 2 * Nzero;
   eV2N = expV(N);
   fprintf(fpexpspect2N, "         m      EVm2N\n");
   for (i = 1; i <= 2 * maxrank; i++){
     fprintf(stdout, "[%d]\n", i);
     fflush(stdout);
     fprintf(fpexpspect2N, "%10d %15.2f\n", i, expVm(N, (double) i));
   }
   fprintf(stdout, "\n");
   fflush(stdout);
   fclose(fpexpspect2N);

   /* PRINT VOCABULARY SIZES */

   fprintf(fpVN, "       V       EV     EV2N\n");
   fprintf(fpVN, "%15.2f %15.2f %15.2f\n", V, eV, eV2N);
   fclose(fpVN);

   /* INTERPOLATION */

   if (nchunks > 0){

     /* CALCULATE THE TEXT CHUNKS */

     chunksize = floor(Nzero/(nchunks*1.0));
     reMainder = Nzero - ((nchunks*1.0) * chunksize);
     for (k = 1; k <= nchunks; k++)   CHUNKS[k] = chunksize;
     for (k = 1; k <= reMainder; k++) CHUNKS[k]++;
     for (k = 2; k <= nchunks; k++)   CHUNKS[k] += CHUNKS[k-1];

     /* AND PRINT THE CORRESPONDING STATISTICS */

     fprintf(stdout, "computing interpolation statistics\n");
     fflush(stdout);
     fprintf(fpint, "       N       EV      EV1      EV2      EV3      EV4      EV5       GV\n");
     for (k = 1; k <= nchunks; k++){
        fprintf(stdout, "[%d]\n", k);
        fflush(stdout);
        x = expV(CHUNKS[k]);
        x1 = expV(CHUNKS[k]+1.0);
        y = expVm(CHUNKS[k], 1.0);
        y2 = expVm(CHUNKS[k], 2.0);
        y3 = expVm(CHUNKS[k], 3.0);
        y4 = expVm(CHUNKS[k], 4.0);
        y5 = expVm(CHUNKS[k], 5.0);
        fprintf(fpint, "%15.2f %15.2f %15.2f %15.2f %15.2f %15.2f %15.2f %15.4f\n", CHUNKS[k], x, y, y2, y3, y4, y5, x1-x);
     }
     fprintf(stdout, "\n");
     fflush(stdout);
   }

   /* EXTRAPOLATION */
 
   if (E == NULL_F) {  /* extrapolate to 2N */
     fprintf(fpext, "       N       EV   EV1      EV2      EV3      EV4      EV5       GV\n");
     fprintf(stdout, "computing extrapolation statistics to 2N\n");
     fflush(stdout);
     for (k = 1; k <= nchunks; k++){
        fprintf(stdout, "[%d]\n", k);
        fflush(stdout);
        x  = expV(Nzero+CHUNKS[k]);
        x1 = expV(Nzero+CHUNKS[k]+1.0);
        y  = expVm(Nzero+CHUNKS[k], 1.0);
        y2 = expVm(Nzero+CHUNKS[k], 2.0);
        y3 = expVm(Nzero+CHUNKS[k], 3.0);
        y4 = expVm(Nzero+CHUNKS[k], 4.0);
        y5 = expVm(Nzero+CHUNKS[k], 5.0);
        fprintf(fpext, "%15.2f %15.2f %15.2f %15.2f %15.2f %15.2f %15.2f %15.4f\n", Nzero+CHUNKS[k], x, y, y2, y3, y4, y5, x1-x);
     }
     fprintf(stdout, "\n");
     fflush(stdout);
   }
   else{

     /* FIND NEW CHUNKSIZES */

     fprintf(stdout, "computing extrapolation statistics to E\n");
     fflush(stdout);
     chunksize = floor((E-Nzero)/(enchunks*1.0));
     reMainder = (E-Nzero) - ((enchunks*1.0) * chunksize);
     for (k = 1; k <= enchunks; k++)   CHUNKS[k] = chunksize;
     for (k = 1; k <= reMainder; k++)  CHUNKS[k]++;
     for (k = 2; k <= enchunks; k++)   CHUNKS[k] += CHUNKS[k-1];

     /* PRINT THE GROWTH CURVE */

     fprintf(fpext, "       N       EV   EV1      EV2      EV3      EV4      EV5       GV\n");
     fprintf(stdout, "computing extrapolation statistics to 2N\n");
     fflush(stdout);
     for (k = 1; k <= enchunks; k++){
        fprintf(stdout, "[%d]\n", k);
        fflush(stdout);
        x  = expV(Nzero+CHUNKS[k]);
        x1 = expV(Nzero+CHUNKS[k]+1.0);
        y  = expVm(Nzero+CHUNKS[k], 1.0);
        y2 = expVm(Nzero+CHUNKS[k], 2.0);
        y3 = expVm(Nzero+CHUNKS[k], 3.0);
        y4 = expVm(Nzero+CHUNKS[k], 4.0);
        y5 = expVm(Nzero+CHUNKS[k], 5.0);
        fprintf(fpext, "%15.2f %15.2f %15.2f %15.2f %15.2f %15.2f %15.2f %15.4f\n", Nzero+CHUNKS[k], x, y, y2, y3, y4, y5, x1-x);
     }
     fprintf(stdout, "\n");
     fflush(stdout);



     /* AND SHOW THE SPECTRUM AT E */

     eV2N = expV(E);
     fprintf(fpE, "         m      EVmXN\n");
     for (i = 1; i <= maxrank; i++){
       fprintf(fpE, "%10d %15.2f\n", i, expVm(E, (double) i));
     }
   }

   if (freemem == 1) {
     free_matrix (sim_mat, 1, ndimensions + 1, 1, ndimensions);
     free_vector (sim_vec, 1, ndimensions + 1);
     free_vector (sim_yy, 1, ndimensions);
   }


   return (0);
} /* end of main */


/* LEXICAL STATISTICS FUNCTIONS */

double square (in)
double in;

{
return (in * in);
}


double expV (n)
double n;
{
  N = n; 
  return (qromb (funcVNy, L_BOUND2, U_BOUND2) * N / (stdev * SQRT2PI));
}

double funcVNy (x) 
double x;

{
  double y,w,z;
 
  z = log (x * Z / N) / stdev;
  w = 1.0 / x;
  y = (1.0 - exp (-x)) * w * w * exp(-0.5 * z * z);
  return (y);
}


double expV1 (n)
double n;
{
  N = n;
  /*
  fprintf(stderr, "N = %f stdev = %f sqrt2pi = %f\n", N, stdev, SQRT2PI);
  fprintf(stderr, "lbound = %f ubound = %f\n", L_BOUND2, U_BOUND2);
  */
  return (qromb (funcV1Ny, L_BOUND2, U_BOUND2) * N / (stdev * SQRT2PI));
}

double funcV1Ny(x) 
double x;
{
 /*
 double xtmp, xtmp1, xtmp2;

 xtmp1 = (1.0/x);
 xtmp2 = square(log(x*Z/N)/stdev);
 fprintf(stderr, "xtmp1 = %30.20f xtmp2 = %30.20f\n", xtmp1, xtmp2);
 xtmp = (1.0/x) * exp( (-1.0*x) - ( (1.0/2.0) * square(log(x*Z/N)/stdev) ) );
 fprintf(stderr, "xtmp = %30.20f\n", xtmp);
 return(xtmp);
 */
 return(
    (1.0/x) *
    exp( (-1.0*x) - ( (1.0/2.0) * square(log(x*Z/N)/stdev) ) )
 );

}


double gm2, factlngm, ZgN;

double expVm (n, m)  /* voor m >= 2 */
double m,n;

{
  gN = n; gm = m;
  gm2 = gm - 2.0;
  factlngm = factln ((int) gm);
  ZgN = Z / gN;
  
  return (qromb (funcVmNy, L_BOUND2, U_BOUND2) * gN / (stdev * SQRT2PI));
}


double funcVmNy (x)   /* m >= 2 */
double x;

{
  return (exp ((gm2 * log(x)) - factlngm) *
          exp ((-x) - (0.5 * square (log (x * ZgN) / stdev))));
}


/* FUNCTIONS FOR FILE AND OPTION HANDLING, AND HELP FUNCTION */

void help ()
{
  fprintf (stderr,"lnreCarr text.spc\n");
  fprintf (stderr,"OPTIONS:\n");
  fprintf (stderr,"     -h: display help\n");
  fprintf (stderr,"     -m: number of ranks in fit (default: 15)\n");
  fprintf (stderr,"     -k: number of chunks for interpolation (default: 20)\n");
  fprintf (stderr,"     -K: number of chunks for extrapolation (default: 20)\n");
  fprintf (stderr,"     -E: extrapolation sample size (default: 2N)\n");
  fprintf (stderr,"     -H: input files lack header (default: with header)\n"); 
  fprintf (stderr,"     -f: calculated only expected spectrum for -f ranks\n"); 
  fprintf (stderr,"     -e: use mse on first -e ranks in simplex cost function\n");
  fprintf (stderr,"     -N: force number of tokens to be N\n");
  fprintf (stderr,"     -V: force number of tokens to be V\n");
  fprintf (stderr,"INPUT:\n");
  fprintf (stderr,"     text.spc:  m Vm\n");
  fprintf (stderr,"OUTPUT:\n");
  fprintf (stderr,"     text_C.spc:   expected spectrum\n");
  fprintf (stderr,"     text_C.fsp:   expected spectrum (only with -f option)\n");
  fprintf (stderr,"     text_C.sp2:   expected spectrum at 2N\n");
  fprintf (stderr,"     text_C.ev2:   E[V(N)] and E[V(2N)]\n");
  fprintf (stderr,"     text_C.sum:   summary, fitted parameters\n");
  fprintf (stderr,"     text_C.int:   interpolation V(N), V(1-5,N)\n");
  fprintf (stderr,"     text_C.ext:   extrapolation V(N), V(1-5,N)\n");
  exit (1);
}


void print_sim_matrix(m, ndim)
double **m;
int ndim;
{
 int i, j;
 fprintf(stderr, "summary of similarity matrix:\n");
 for (i = 1; i <= ndim+1; i++){
   for (j = 1; j <= ndim; j++){
       fprintf(stderr,"%15.2f ", m[i][j]);
   }
   fprintf(stderr, "%4.2f ", sim_vec[i]);
   Z = m[i][1]; stdev = m[i][2];
   eV = expV(N);
   eV1 = expV1(N);
   fprintf(stderr, "eV = %6.2f (V = %6.0f)  eV1 = %6.2f (V1 = %6.0f)\n", eV, V, eV1, n1);
 }
 fprintf(stderr, "end of summary\n");
}


double sim_functie_mse(x)
double *x;
{
  extern double getmse();
  double simMSE;

  Z = x[1]; stdev = x[2];
  if (Z <= 0) { Z = 1; }
  if (stdev <= 0) { stdev = 0.01; }


  /* calculate MSE for the first msenranks given the parameter values in x */
  simMSE = getmse();
  return(simMSE);
}

double sim_functie (x)
double	*x;

{
  Z = x[1];
  stdev = x[2];
  if (Z <= 0) {
    Z = 1;
  }

  if (stdev <= 0) {
    stdev = 0.01;
  }


  eV = expV (N);
  eV1 = expV1 (N);


  return (fabs (V - eV) + fabs (n1 - eV1));
}


double getVn (r) 
int r;
{
   int i;
   for (i = r; (int) SPECTRUM[i][0] > r; i--) ;
   if ((int) SPECTRUM[i][0] == r) return(SPECTRUM[i][1]);
   else return(0.0);
}

double getmse (){
   extern double getVn ();
   extern double expV1 ();
   extern double expVm ();
   extern double expV ();
   
   double som, som2, esom2, EVn, Vn, x, y, EV;
   int i;
   
   som = 0.0; som2 = 0.0; esom2 = 0.0; 


   x = expV1(N); y = getVn(1);
   eV1 = x;
   som += (x-y)*(x-y);
   esom2 += x; som2 += y; 

   for (i = 2; i <= msenranks; i++) {
        EVn = expVm (N, (double)i);
        Vn = getVn(i);
        som2 += Vn; esom2 += EVn;
        som += (EVn-Vn)*(EVn-Vn);
   }
   EV = expV(N);
   x = EV - esom2; y = V - som2;
   som += (x-y)*(x-y);
   som += (EV-V)*(EV-V);
   return(som/((double)(msenranks+2)));
}

