#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_CHAR 10
#define SUCCESS 0
#define ERROR_ARGUMENT_NUMBER 1
#define ERROR_CANNOT_OPEN_FILE 2
#define ERROR_CANNOT_CLOSE_FILE 3

char *ErrorMessage[4] = {
	"成功",
	"ファイル名を指定してください。",
	"ファイルを開けませんでした。",
	"ファイルを閉じれませんでした。"
};

int main(int argc, char* argv[]){
	FILE *fp;
	int i = 0, j = 0;
	char buffer[MAX_CHAR];
	char c;
	char **line = NULL,**lineInitialValue = NULL;
	int lineCount = 0;
	int result = SUCCESS;
	int surplus = 0;
	int *line1 = NULL, *line2 = NULL;
	
	if (argc != 2){
		result = ERROR_ARGUMENT_NUMBER;
	} else {
		fp = fopen(argv[1], "r");
		if (fp == NULL) {
				result = ERROR_CANNOT_OPEN_FILE;
		} else { 
			while (EOF != (c = getc(fp))){
				if (c == '\n') {
					lineCount++;
					surplus = 0;
				} else {
					surplus++;
				}
			}
			if (surplus != 0) {
				lineCount++;
			}
			rewind(fp);
			lineInitialValue = (char **)calloc(lineCount, sizeof(char *));
			line = lineInitialValue;
			
			while (EOF != (c = getc(fp))) {
				if ( (c == '\n') || ((c == EOF) && (i != 0))) {
					if ( c == EOF){
						i--;
					} else {
						buffer[i] = c;
					}
					buffer[i + 1] = '\0';
					*line = (char*)malloc((MAX_CHAR - 1) * j + i + 2);
					if (j == 0) {
						strcpy(*line, buffer);
					} else {
						strcpy(*line, line1);
						strcat(*line, buffer);
						if (line1) {
							free(line1);
						}
						line1 = NULL;
					}
					line++;
					i = 0;
					j = 0;
				} else {
					buffer[i] = c;
					if (i < MAX_CHAR - 2) {
						i++;
					}
					else {
						buffer[MAX_CHAR - 1] = '\0';
						if (!line1) {
							j++;
							line1 = (char*)malloc((MAX_CHAR - 1) * j + 1);
							strcpy(line1, buffer);
						} else {
							j++;
							line2 = (char*)malloc((MAX_CHAR - 1)*j + 1);
							line2[0] = '\0';
							strcat(line2, line1);
							strcat(line2, buffer);
							if (line1) {
								free(line1);
							}
							line1 = line2;
						}
						i = 0;
					}
				}
			}
			if ( 0 != fclose(fp)){
				result = ERROR_CANNOT_CLOSE_FILE;
			}
		}
	}
	
	line = lineInitialValue;
	for (i = lineCount - 1; i >= 0; i--){
		printf(line[i]);
	}

	for (i = 0; i < lineCount; i++) {
		if (line[i]) {
			free(line[i]);
		}
	}
	if (lineInitialValue) {
		free(lineInitialValue);
	}
	
	if (result != SUCCESS){
		printf("%s\n", ErrorMessage[result]);
	}
	return result;
}
