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




int
compare(const void *p1, const void *p2){

	char *p1Ptr = *(char **) p1;
	char *p2Ptr = *(char **) p2;

	char *line1 = malloc(80*sizeof(char));
	char *line2 = malloc(80*sizeof(char));

	strcpy(line1, p1Ptr);
	strcpy(line2, p2Ptr);

	int key1 = atoi(strtok(line1, " "));
	int key2 = atoi(strtok(line2, " "));

	printf("%d %d", key1,key2);

	if(key1 < key2){
		return -1;
	}
	else if(key1 > key2){
		return 1;
	}
	else{
		return 0;
	}
	
}



int
main(int argc, char *argv[]){


	int rowAmount = 0;

	// check to make sure the right number of command line arguments are present

	if(argc != 2){
		fprintf(stderr, "Usage: mysort <filename>\n");
		exit(1);
	}

	FILE *fp;
	fp = fopen(argv[1],"r");

	if(fp == NULL){
		fprintf(stderr, "Error: Cannot open file\n");
		exit(1);
	}

	char line[80];

	// run throught the file to check how many lines there are
	while(fgets(line, 82, fp) != NULL){
		rowAmount++;
	}
	fclose(fp);

	// reopen the file in order to read it in
	fp = fopen(argv[1], "r");

	char *rows[rowAmount];
	int count = 0;
	char *ap;

	// read through the file and place the lines in the array of strings
	while(fgets(line, 81, fp) != NULL){
		if(strlen(line) > 80){
			fprintf(stderr,"Error: Line too long\n");
			exit(1);
		}
		else{
			ap = malloc((strlen(line))*sizeof(char));
			strcpy(ap, line);
			rows[count] = ap;

			count++;
		}
	}

	qsort(rows, rowAmount,sizeof(char*), compare);

	int i;
 	for(i=0; i < rowAmount; i++){
	  printf(rows[i]);
    }
	printf("\n");

	fclose(fp);

	return 0;
}
