#include <stdlib.h>

#include "tree.h"
#include "fgetword.h"
#include "readpts.h"

coord *readpoints(char *pointsfile,
		  double *a,
		  double *b,
		  int *n,
		  coord *points
		  )
{
  int i=0;
  char word[MAXWORD];

  FILE *fopen(), *datafile;

  datafile = fopen(pointsfile,"r");  /* Open datafile to find out how many 
				       numbers are in it. */
  for(i=0; i<=MAXLEN && (fgetword(datafile,MAXWORD,word)!=0); ++i){
    if(fgetword(datafile,MAXWORD,word)!=0)
      ;
    else{
      fprintf(stderr,"Incomplete data file.  There must be an even ");
      fprintf(stderr,"number of numbers.\n");
      exit(2);
    }	
  }
  if(i>=MAXLEN){
    printf("Too much data.  ");
    printf("Please restrict data in file to a maximum of ");
    printf("%d items (or recompile after changing ",(int) MAXLEN);
    printf("the value of MAXLEN).\n");
  }
  else{
    *n=i-1;
    fclose(datafile);                /* Don't forget to close the file! */

    points = (coord *) calloc(*n, sizeof(coord));

    if(points==NULL){
      printf("Out of memory");
      exit(1);
    }
    datafile = fopen(pointsfile,"r");  /* Open datafile to read the numbers 
				       this time */
    if(fgetword(datafile,MAXWORD,word)!=0)
      sscanf(word,"%lf",a);
    else{
      fprintf(stderr,"Incomplete data file.  File is empty!\n");
      exit(2);
    }
    if(fgetword(datafile,MAXWORD,word)!=0)
      sscanf(word,"%lf",b);
    else{
      fprintf(stderr,"Incomplete data file.  ");
      fprintf(stderr,"File contains only one number!\n");
      exit(2);
    }
    for(i=0; (fgetword(datafile,MAXWORD,word)!=0); ++i){
      sscanf(word,"%lf",&(points[i].x));
      if(fgetword(datafile,MAXWORD,word)!=0)
	sscanf(word,"%lf",&(points[i].y));
      else{
	fprintf(stderr,"Incomplete data file.  There must be an even ");
	fprintf(stderr,"number of numbers.\n");
	exit(2);
      }
    }
    fclose(datafile);                /* Don't forget to close the file! */
  }

  return points;
}
    
