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

#include "merge_sort.h"
#include "insertion_sort.h"


/*
 *  Program to be called as
 * 
 *  ./sort_file <filename>
 * 
 */

int main(int argc, char **argv)
{
    FILE *infile;
    double x;
    double *A;
    int i, m, count = 0;
  
    if (argc != 2) {
	printf("\n\nUsage: ./sort_file <filename>\n\n");
	return 1;
    }
    infile = fopen(argv[1], "r");
    if (infile == NULL) {
	printf("Error: No such file '%s' exists.\n", argv[1]); 
	return 1;
    }
    while (!feof(infile)) {
	m = fscanf(infile, "%lf", &x);
	if (m == 1) count++;
    }
    fclose(infile);

    /* open file again to read in data into array */
    A = (double*) malloc(count * sizeof(double));
    infile = fopen(argv[1], "r");
    for (i = 0; i < count; i++) {
	fscanf(infile, "%lf", &A[i]);
	/* printf("%lf\n", A[i]); */
    }
    fclose(infile);

    /* sort and print sorted output */
    merge_sort(A, 0, count-1);
    for (i = 0; i < count; i++) {
	printf("%lf\n", A[i]);
    }

    free(A);
    return 0;
}


