#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 8388608
#define MAXWORD 100

void sort(void *v[], long n, double (*comp)(void *,void *));
long getdata(char *dataloc, float v[]);
double compare(float *left,float *right);
char *fgetword(FILE *datafile, int n, char word[]);

void *calloc(size_t n, size_t size);

main(int argc, 
     char *argv[]
     )
{
  float *data;            /* An array to hold the data (an array of floats 
			     in this example) */
  float **pdata        ;   /* An array of pointers, each of which points 
			     to an element of data.  The pointers are 
			     sorted, not the data itself.  This is so that 
			     if the data is a big structure we do not have 
			     to read and write it each time it is 
			     swapped. */
  long length,i;          /* length is the length of the number of data 
			     objects. */


  if (argc <= 1)          /* No command line input */
    printf("There was no specified input!\n");
  else {
    data = (float *) calloc(MAXLEN,sizeof(float));
    if(data==NULL)
      printf("Out of memory");
    else{
      /*    *data = 432.3245;
	    data[1] = 326.2435;
	    data[2] = 2345.532; */
      length = getdata(argv[1],data);   /* Read the specified file */
      if(length>=(MAXLEN-1)){          /* More input than this can deal with */
	printf("Too much data! Change the value of MAXLEN and all the\n");
	printf("integers to longs in the code, then try again.\n  Note: ");
	printf("If you were trying to sort less than %d numbers\n it ",MAXLEN);
	printf("means that there is a problem!");
      }
      else {
	pdata = (float **)calloc(length,sizeof(float *));
	for(i=0;i<length;++i)
	  pdata[i]=&data[i];         /* Set the pointers */
	sort((void **) pdata,length,
	     (double (*)(void *,void *))(compare));  /* Sort the pointers */
	/*      printf("%d\n",length);*/
	for(i=0;i<length;++i)
	  printf("%d %f\n",i+1,*pdata[i]);      /* Print the sorted file */
	free(pdata);
      }
      free(data);
    }
  }
}
long getdata(char *dataloc, 
	     float v[]
	     )
{
  long length,i;
  char word[MAXWORD];
  FILE *fopen(), *datafile;

  datafile = fopen(dataloc,"r"); /* dataloc is the name of the file 
				    containing the data.  It was passed 
				    by the calling routine */
  for(i=0; i<=MAXLEN && (fgetword(datafile,MAXWORD,word)!=NULL); ++i)
      sscanf(word,"%f",v+i);

  fclose(datafile);                 /* Don't forget to close the file! */
  length = i;
  return length;                  /* Number of data points returned */
}
  /*
    while(((tmp=getc(datafile))!= EOF) && i<=MAXLEN){
     ungetc(tmp,datafile);
     fscanf(datafile,"%f",&(v[i++]));
  }*/


double compare(float *left, 
	      float *right
	      )
{
  return(*right-*left);
}




