#pragma once
#include "../../stdafx.h"

void normalize_newlines(char* source) {
	unsigned long index_read = 0;
	unsigned long index_write = 0;
	while (true) {
		if (source[index_read]=='\r') {
			source[index_read] = '\n';
			if (source[index_read+1]=='\n') index_read++;
		}
		else if (source[index_read]=='\0') break;
		source[index_write] = source[index_read];
		index_read++;
		index_write++;
	}
	source[index_write] = '\0';
}
//TODO: const char*?
char* file_get_file(const char* path, bool normalize=true) {
	//Open the file.
	FILE* file = fopen(path,"rb");
	if (file==NULL) {
		return NULL;
	}
		
	//Find the end of the file
	fseek(file,0,SEEK_END);
	long file_size = ftell(file) / sizeof(char);
	rewind(file);

	//This will be more than we need for multi-line files, as fread ignores
	//some whitespace line terminators.  The +1 is for the '\0' character, and
	//is necessary only if there are no line separators in the file.
	char* buffer = (char*)malloc(sizeof(char)*(file_size+1));
	#ifdef GLLIB_ERROR_MODE_REPORT_ERRORS
	if (buffer == NULL) {
		throw glLibError("File \""+string(path)+"\" is too large to fit in available memory!");
	}
	#endif

	//Copy the file into the buffer:
	size_t result = fread(buffer,1,file_size,file);

	fclose(file);

	buffer[result] = '\0';

	if (normalize) normalize_newlines(buffer);

	return buffer;
}