#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <string.h>
#include <ctype.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));

	int invalidKey = 0;
	int key1;
	int key2;

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

	char *firstBlock;
	int i = 0;
	firstBlock = strtok(line1, " \n\t");

	if(firstBlock == NULL){
		key1 = 0;
	}
	else{

	if(*firstBlock == '-'){
		i = 1;
	}
	
	

	//printf("before for loop: %s\n", firstBlock);
	for(; *(firstBlock + i) != '\0'; i++){
		//printf("%c ", *(firstBlock+i));

		if(*(firstBlock + i) == '\n'){
			break;
		}
		else if(isdigit(*(firstBlock + i)) == 0){
			//printf("invalid key\n");
			invalidKey = 1;
		}
 	}

	if(invalidKey == 0){
		//printf("after for loop: %s\n", firstBlock);
		key1 = atoi(firstBlock);
	}
	else{
		//printf("Invalid Key\n");
		key1 = 0;
	}

//	printf("%d\n ", key1);
}
	invalidKey = 0;
	firstBlock = strtok(line2, " \n\t");

	if(firstBlock == NULL){
		key2 = 0;
	}
	else{	
	i = 0;

	if(*firstBlock == '-'){
		i = 1;
	}

	//printf("before for loop: %s\n", firstBlock);
	for(; *(firstBlock + i) != '\0'; i++){
		//printf("%c ", *(firstBlock + i));

		if(*(firstBlock + i) == '\n'){
			break;
			//*(firstBlock + i) = ' ';
		}

		if(isdigit(*(firstBlock + i)) == 0){
			invalidKey = 1;
      }
	}


	if(invalidKey == 0){
		//printf("after for loop: %s\n", firstBlock);
		key2 = atoi(firstBlock);
	}
	else{
		key2 = 0;
	}
}
	//printf("%d\n", 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[100];

	// 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, 85, fp) != NULL){
		if(strlen(line) > 80){
			fprintf(stderr,"Error: Line too long\n");
			exit(1);
		}
		else{
			ap = malloc((strlen(line)+1)*sizeof(char));
			strcpy(ap, line);
			rows[count] = ap;
			//printf("%s", rows[count]);
			count++;
		}
//		 printf("%s", rows[count-1]);
	}

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

//	printf("\n");

	qsort(rows, rowAmount,sizeof(char*), compare);
	
	//printf("Final Output\n");

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

	fclose(fp);

	return 0;
}
