/*
 *	File: lnreZipf.c
 *
 *      (C) IWTS
 *          KU Nijmegen
 *          The Netherlands
 *
 *      Author: R. Harald Baayen
 *
 *      History:
 *
 *      - feb 1997, version 1.0
 *
 *      Description: runs extended Zipf's law
 *
 *      Extended  November 1999 with Kyo Kageura's estimation method for
 *      VZ; this estimation method sometimes gives improved fits.  It is
 *      enabled by using the -O option.
 *
 */

#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	expV ();
extern double	expVm ();
extern double	funcVm ();
extern double	getZ2 ();
extern double	qromb ();
extern double   harmonic(int);  /* Addition by Kyo Kageura */

/* 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 */
         pstar,                     /* maximum relative frequency */
         mmax,                      /* highest frequency rank */
         mrank,                     /* word frequency, used in expVm() */
         SPECTRUM[MAXM1][3],        /* frequency spectrum m Vm EVm */
         Z, VZ,                     /* Zipf size, and V(Z) */
         Nzero, Vzero,              /* original sample size N0 */
         eV, eV2N, S,               /* E[V(N)], E[V(2N)], S */
         eV1, eV2, 
         CHUNKS[MAXCHUNKS3],        /* the chunk sizes */
         chunksize, remainDer,      /* chunk variables */
         x, x1, y, y2, y3, y4, y5,
	     u_bound;		            /* upper integration intervals */

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 */
         *fullspc,		            /* full spectrum .fsp for m=1..skip */
         *fpint,                    /* interpolation results */
         *fpext,                    /* extrapolation results */
         *fpE;                      /* spectrum at sample size E */

int      nranks,                    /* number of different ranks in spectrum */
         maxrank,                   /* largest rank for fit, default 15 */
         i, j,                      /* counter */
         oldEstimationOfZ,          /* if 1, use m* method for estimation of
									   VZ; the default. Otherwise: Kyo's 
									   summation method */
         header,                    /* boolean for presence of header */
         k,                         /* variable for chunks */
         skip,			            /* print spectrum only, for m=1..skip */
         nchunks,                   /* number of chunks for interpolation */
         enchunks,                  /* number of chunks for extrapolation */
         token, type,               /* auxiliary variables for scanf */
         aantal;                    /* for command line options */

char     woord[MAXWORDLENGTH],      /* variable for skipping header in fscanf */
         new_name[MAXWORDLENGTH],   /* variables for extension handling    */
         base_name[MAXWORDLENGTH],
         *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;
   skip = 0;
   E = NULL_F;
   u_bound = U_BOUND;
   oldEstimationOfZ = 1;             /* default: use log(pstar Z) to estimate
										VZ; if 0: use Kyo's summation method */

   /* 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 '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, "lnreZipf: cannot skip with zero rank\n");
                  exit(1);
                }
                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 'i':
                u_bound = (double) leesgetal (fs, &aantal);
                for (; aantal > 0; aantal--){
                   fs++;
                }
                break;
            case 'm':
                maxrank = leesgetal (fs, &aantal);
                for (; aantal > 0; aantal--){
                   fs++;
                }
                break;
			case 'O': 
				oldEstimationOfZ = 0;  /* use Kyo's summation method */
				break;
            case 'H':      /* input files without headers! */
                header = 0;
                break;
            default:
                fprintf (stderr, "lnreZipf: illegal option %c\n", *fs);
                exit (1);
                break;
            }
        }
   } /* of while */

   /* FILE HANDLING */

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

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

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

   /* file name handling output files */

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

 if (skip == 0) {
   change_extension (base_name, new_name, "_Z.spc");
   if ((fpexpspect = fopen(new_name, "w")) == NULL){
      fprintf(stderr, "lnreZipf: can't open output file %s\n", new_name);
      exit(1);
   }
   change_extension (base_name, new_name, "_Z.sp2");
   if ((fpexpspect2N = fopen(new_name, "w")) == NULL){
      fprintf(stderr, "lnreZipf: can't open output file %s\n", new_name);
      exit(1);
   }
   change_extension (base_name, new_name, "_Z.ev2");
   if ((fpVN = fopen(new_name, "w")) == NULL){
      fprintf(stderr, "lnreZipf: can't open output file %s\n", new_name);
      exit(1);
   }
   change_extension (base_name, new_name, "_Z.sum");
   if ((fpsum = fopen(new_name, "w")) == NULL){
      fprintf(stderr, "lnreZipf: can't open output file %s\n", new_name);
      exit(1);
   }
   change_extension (base_name, new_name, "_Z.int");
   if ((fpint = fopen(new_name, "w")) == NULL){
      fprintf(stderr, "lnreZipf: can't open output file %s\n", new_name);
      exit(1);
   }
   change_extension (base_name, new_name, "_Z.ext");
   if ((fpext = fopen(new_name, "w")) == NULL){
      fprintf(stderr, "lnreZipf: can't open output file %s\n", new_name);
      exit(1);
   }
   if (E > NULL_F){
     change_extension (base_name, new_name, "_Z.sp3");
     if ((fpE = fopen(new_name, "w")) == NULL){
        fprintf(stderr, "lnreZipf: can't open output file %s\n", new_name);
        exit(1);
     }
   }
  } else { /* skip == 1 */
      change_extension (base_name, new_name, "_Z.fsp");
      if ((fullspc = fopen(new_name, "w")) == NULL){
           fprintf(stderr, "lnreZipf: can't open output file %s\n", new_name);
           exit(1);
      }
      change_extension (base_name, new_name, "_Z.sum");
      if ((fpsum = fopen(new_name, "w")) == NULL){
           fprintf(stderr, "lnreZipf: can't open output file %s\n", new_name);
           exit(1);
      }
  }

   /* LOAD SPECTRUM FILE */

   nranks = 0; n1 = 0; n2 = 0;
   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];
   pstar = mmax / N;
   Nzero = N; Vzero = V;

   /* DETERMINE THE PARAMETER OF THE MODEL */

   if (oldEstimationOfZ == 0) {  /* Kyo Kageura's enhanced estimation method */
       Z = getZ2 (pstar, Nzero, Vzero, N, 1);
	   VZ = Z/harmonic(floor(pstar*Z));
   } else {
       Z = getZ2 (pstar, Nzero, Vzero, N, 0);
       VZ = Z / log (pstar * Z);
   }

   /* AND CALCULATE E[V(N)] AND E[V(m,N)] ;  NOTE: S IS INFINITE */

   fprintf(stdout, "computing expected spectrum at N\n");
   fflush(stdout);
   eV = expV(Nzero);
   S = NULL_F;

   if (skip==0) {
      for (i = 1; i <= maxrank; i++) {
        fprintf(stdout, "[%d]\n", i);
        fflush(stdout);
        SPECTRUM[i][2] = expVm((double) i, Nzero);
      }
   } else {

      eV1 = expVm(1.0, Nzero);
      fprintf(fullspc, "%d %10.2f\n", 1, eV1);
      fprintf(stdout, "[%d]\n", 1);
      fflush(stdout);

      eV2 = expVm(2.0, Nzero);
      fprintf(fullspc, "%d %10.2f\n", 2, eV2);
      fprintf(stdout, "[%d]\n", 2);
      fflush(stdout);

      for (i = 3; i <= skip; i++) {
        fprintf(stdout, "[%d]\n", i);
        fflush(stdout);
        fprintf(fullspc, "%d %10.2f\n", i, expVm((double) i, Nzero));
      }
      fclose(fullspc);
   }
   fprintf(stdout, "\n");
   fflush(stdout);

   /* PRINT SUMMARY */

   fprintf(fpsum, "Zipf's Zeta model for %s\n", *argv);
   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", eV1);
   fprintf(fpsum, "V(2,N)    = %12d\n", (int) n2);
   fprintf(fpsum, "E[V(2,N)] = %12.4f\n", eV2);
   fprintf(fpsum, "S         =     infinite\n");
   fprintf(fpsum, "Z         = %12.5f\n",  Z);
   fprintf(fpsum, "beta      = 1.0\n");
   fprintf(fpsum, "VZ        = %12.5f\n",  VZ);
   fclose(fpsum);

   if (skip>0) {
      exit(1);
   }

   /* 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, "%10.4f %10.4f %10.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((double) i, N));
   }
   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   Alpha1      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(1.0, CHUNKS[k]);
        y2 = expVm(2.0, CHUNKS[k]);
        y3 = expVm(3.0, CHUNKS[k]);
        y4 = expVm(4.0, CHUNKS[k]);
        y5 = expVm(5.0, CHUNKS[k]);
        fprintf(fpint, 
           "%15.2f %15.2f %15.4f %15.2f %15.2f %15.2f %15.2f %15.2f %15.4f\n", 
           CHUNKS[k], x, y/x, y, y2, y3, y4, y5, x1-x);
     }
     fprintf(stdout, "\n");
     fflush(stdout);

   }

   /* EXTRAPOLATION */
  
   if (E == NULL_F) {  /* extrapolate to 2N */
     fprintf(stdout, "computing extrapolation statistics to 2N\n");
     fflush(stdout);
     fprintf(fpext, "         N         EV        EV1      EV2      EV3      EV4      EV5\n");

     for (k = 1; k <= nchunks; k++){
        fprintf(stdout, "[%d]\n", k);
        fflush(stdout);
        x = expV(Nzero+CHUNKS[k]);
        y = expVm(1.0, Nzero+CHUNKS[k]);
        y2 = expVm(2.0, Nzero+CHUNKS[k]);
        y3 = expVm(3.0, Nzero+CHUNKS[k]);
        y4 = expVm(4.0, Nzero+CHUNKS[k]);
        y5 = expVm(5.0, Nzero+CHUNKS[k]);
        fprintf(fpext, "%15.2f %15.2f %10.4f ", Nzero+CHUNKS[k],  x, y);
        fprintf(fpext, "%15.2f %15.2f %15.2f %15.2f\n", y2, y3, y4, y5);
     }
     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(stdout, "computing extrapolation statistics to E\n");
     fflush(stdout);
     fprintf(fpext, "         N         EV        EV1      EV2      EV3      EV4      EV5\n");

     for (k = 1; k <= enchunks; k++){
        fprintf(stdout, "[%d]\n", k);
        fflush(stdout);
        x = expV(Nzero+CHUNKS[k]);
        y = expVm(1.0, Nzero+CHUNKS[k]);
        y2 = expVm(2.0, Nzero+CHUNKS[k]);
        y3 = expVm(3.0, Nzero+CHUNKS[k]);
        y4 = expVm(4.0, Nzero+CHUNKS[k]);
        y5 = expVm(5.0, Nzero+CHUNKS[k]);
        fprintf(fpext, "%15.2f %15.2f %10.4f ", Nzero+CHUNKS[k],  x, y);
        fprintf(fpext, "%15.2f %15.2f %15.2f %15.2f\n", y2, y3, y4, y5);
     }
     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((double) i, E));
     }
   }

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


double expV (n)
double n;
{
  N = n;
  /* return( (Z*N*log(N/Z))/( (N-Z) * log(pstar * Z))); */
  /* Kyo Kageura modification */
  return( VZ * ( N / (N-Z) ) * log(N/Z) );
}


double expVm (m, n)
double m, n;  
{
  mrank = m;
  N = n;
  return (qromb (funcVm, L_BOUND, u_bound) * VZ * N / Z);
}


double funcVm (x)
double x;
{
 return (x / (exp ((mrank+1.0) * log(1.0+x) )  *  (1.0 +  (x*N/Z))));
}


void help ()
{
  fprintf (stderr, "lnreZipf 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, "     -O: use summation estimation method for VZ\n");
  /* addition for Kyo's method */
  fprintf (stderr, "     -s: only calculate expected spectrum up to rank -s, output on text_Z.fsp\n");
  fprintf (stderr, "INPUT:\n");
  fprintf (stderr, "     text.spc:  m Vm\n");
  fprintf (stderr, "OUTPUT:\n");
  fprintf (stderr, "     text_Z.spc:  expected spectrum\n");
  fprintf (stderr, "     text_Z.fsp:  expected spectrum (s option)\n");
  fprintf (stderr, "     text_Z.sp2:  expected spectrum at 2N\n");
  fprintf (stderr, "     text_Z.ev2:  E[V(N)] and E[V(2N)]\n");
  fprintf (stderr, "     text_Z.sum:  summary, fitted parameters\n");
  exit (1);
}
