#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define DIST  50
#define MAXSIZE 200

/*****************************************

file: makehist.c
Usage: makehist infile outfile

infile is a time file, containing columns of burst lengths
and convergence times separated by a space. Outputfile will
be written with a histogram of the convergence times.

*****************************************/

void main(int argc, char *argv[]) {
  FILE *fin, *fout;
  int burst;
  int value;
  int hist[DIST], i, index;
  double table[MAXSIZE];
  double mean, variance, total, maxvalue, quant;

  if(argc < 2) {
    exit(-1);
  }

  if((fin = fopen(argv[1], "r")) == NULL) {
    fprintf(stderr,"Error opening %s\n", argv[1]);
    exit(-1);
  }
  if((fout = fopen(argv[2], "w")) == NULL) {
    fprintf(stderr,"Error opening %s\n", argv[2]);
    exit(-1);
  }

  for(i = 0; i < DIST; i++)
    hist[i] = 0;
  

  /* First compute maximum value */

  maxvalue = index = 0;
  while(1) {
    
    if((fscanf(fin, "%d %d\n",&burst, &value)) != 2) {
      break;
    }
    if(value > maxvalue)
      maxvalue = value;
    table[index++] = value;
  }
  /* Define quantization factor */

  quant = maxvalue / (DIST - 1);

  /* Now generate histogram */

  for(i = 0; i < index; i++) {
    hist[(int) (table[i] / quant)] += 1;
  }

  for(i = 0; i < DIST; i++) {
    fprintf(fout,"%f %d\n",i*quant,hist[i]);
  }

  /* Compute mean */
  mean = total =  0;
  for(i = 0; i < DIST; i++) {
    mean += i *quant* hist[i];
    total += hist[i];
  }
  mean /= total;
  
  printf("Mean is %f \n",mean);

  /* Compute variance */
    
  variance = 0;
  for(i = 0; i < DIST; i++) {
    variance += (i*quant - mean) * (i*quant - mean)* hist[i];
  }
  variance /= total;
  
  printf("s.d. is %f frames\n",sqrt(variance));

  fclose(fin);
  fclose(fout);

  exit(0);
}
  

