// main.cpp
// ````````

#include <cstdio>

#include "pexl.h"
#include "platform.h"

int usage() {
	fputs(
		"Usage: pxc [options] \n"
		"\n"
		"    -i {filename|-}      Add input file to compile\n"
		"    -o {filename|-}      Set output file\n"
		"    -O0                  Disable optimisations\n"
		"    -O2                  Enable optimisations\n"
		"    --verbose            Verbose\n",
		stderr
	);
	return 1;
}

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

	/*
	Test vectors: (Alt+Shift+5 in VS with SetProjectCommandLineArguments extension)

	--verbose -O2 -i ../pxl-tests/test23.pxl -o ../pxl-tests/tmp.asm
	*/

	FILE* foutput = stdout;
	bool  verbose = false;
	bool  optimise = true;
	bool  got_input = false;

	std::string content;
	std::string set_working_dir = ".";
	
	for (int i = 1; i < argc; ++i) {

		if (!strcmp(argv[i], "--verbose")) {
			verbose = true;

		} else if (!strcmp(argv[i], "-i")) {
			content += file_get_contents(argv[++i]);

			if (strcmp(argv[i], "-")) { // path != '-'
				set_working_dir = dirname_from_path(argv[i]);
			}
			got_input = true;

		} else if (!strcmp(argv[i], "-O0")) {
			optimise = false;

		} else if (!strcmp(argv[i], "-O2")) {
			optimise = true;

		} else if (!strcmp(argv[i], "-o")) {
			char* outputname = argv[++i];
			if (outputname[0] == '-' && outputname[1] == '\0') {
				foutput = stdout;
			} else {
				foutput = fopen(outputname, "wb");
				if (foutput == NULL) {
					fprintf(stderr, "Couldn't open file \"%s\" for output\n", outputname);
					return 1;
				}
			}

		} else {
			return usage();

		}

	}

	if (!got_input || !content.length()) {
		fprintf(stderr, "Nothing to compile\n");
		return 1;
	}
	
	// Compile
	set_working_directory(set_working_dir.c_str());
	std::string ret = pexl_compile(PEXL_X86_NASM, content, verbose, optimise);

	// Write output
	fputs(ret.c_str(), foutput);

	return 0;
}