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

#include "array.h"

#define IODASH "-"

void usage(char* prog) {
	fprintf(stderr, "Usage: %s [-f|--input-file <input-file>] [-o|--output-file <output-file>]\n", prog);
}

int main(int argc, char **argv) {
	char* input_file = IODASH;
	char* output_file = IODASH;

	int c = 0;

	while (1) {
		static struct option long_options[] = {
			{"input-file", required_argument, 0, 'f'},
			{"output-file", required_argument, 0, 'o'},
		};

		int option_index = 0;

		c = getopt_long(argc, argv, "f:o:", long_options, &option_index);

		if (c == -1) {
			break;
		}

		switch (c) {
		case 'f':
			input_file = optarg;
			break;
		case 'o':
			output_file = optarg;
			break;
		default:
			usage(argv[0]);
			return 1;
		}
	}

	if (strcmp(input_file, IODASH) == 0) {
		fprintf(stderr, "(reading from stdin)\n");
	}

	if (strcmp(output_file, IODASH) == 0) {
		fprintf(stderr, "(writing to stdout)\n");
	}

	printf("input_file='%s' output_file='%s'\n", input_file, output_file);

	FILE* instream;

	instream = stdin;
	if (strcmp(input_file, IODASH) != 0) {
		instream = fopen(input_file, "r");
	}

	if (instream == NULL) {
		perror("opening input file");
		return EXIT_FAILURE;
	}

	FILE* outstream;

	outstream = stdout;
	if (strcmp(output_file, IODASH) != 0) {
		outstream = fopen(output_file, "r");
	}

	if (outstream == NULL) {
		perror("opening output file");
		return EXIT_FAILURE;
	}

	int line_int;
	ssize_t nread;

	char* endptr = NULL;
	char* line = NULL;
	size_t len = 0;

	IntArray accum;
	IntArray_new(&accum, 100);

	while ((nread = getline(&line, &len, instream)) != -1) {
		IntArray_append(&accum, atoi(line));
	}

	printf("Accumulated %i ints\n", IntArray_length(&accum));

	IntArray_mergesort(&accum);

	printf("Merge sorted:\n");

	for (int i = 0; i < accum.used; ++i) {
		printf("%i: %i\n", i, IntArray_get(&accum, i, 0));
	}

	if (strcmp(input_file, IODASH) != 0) {
		fclose(instream);
	}

	if (strcmp(output_file, IODASH) != 0) {
		fclose(outstream);
	}

	return EXIT_SUCCESS;
}
