#include <stdio.h>
#include <stdlib.h>
#include "tree1.h"
#include "timer.h"

static FILE *resout;

struct AGG {
    int level;
    int count;
    double sum;
    };

int cmpare(char *p1,char *p2){
   struct AGG *a1 = (struct AGG*)p1;
   struct AGG *a2 = (struct AGG*)p2;

   if(a1->level < a2->level)return(1);
   else if(a1-> level > a2->level)return(-1);
   else return(0);
}

int printsumm(char *p){
   struct AGG *a = (struct AGG*)p;
   printf("%d\t%lf\n",a->level,a->sum/(double)(a->count));
}

int writemns(char *p){
   double mean;
   struct AGG *a = (struct AGG*)p;
   mean = a->sum/(double)(a->count);
   fwrite(&mean,sizeof(double),1,resout);
   }

main(){

   char *head=NULL;
   char filename[100];
   int i,g,n=0;
   double x;
   struct AGG agg, *t;
   FILE *fp;

   fprintf(stderr,"Name of file? ");
   scanf("%s", filename);

   if((fp = fopen(filename,"r")) == NULL){
        fprintf(stderr,"Can't open file %s\n",filename);
        exit(1);
        }

   TIME0

   while(1){
      i = fscanf(fp,"%d %lf",&g,&x);
      n++;
      if(i == EOF)break;
      agg.count = 0;
      agg.level = g;
      t = (struct AGG*)insert(&head,(char*)&agg,sizeof(agg),cmpare);
      t->sum += x;
      t->count++;
      }

    unlink("agg1.out");
    resout = fopen("agg1.out","a");

    traverse(head,printsumm); 
//    traverse(head,writemns);

    TIME1('aggregate')

}   
       

      
 
   



