// Jass_convert_C++.cpp: определяет точку входа для консольного приложения.
//

#include "stdafx.h"

#include "Converter.h"
#include "OutputCode.h"

sOutputCode vFileHeader;
sOutputCode vFileCpp;

int _tmain(int argc, _TCHAR* argv[])
{
	char FileName[200];
	char FullPath[200];
	char Path2[100];
	FILE * pFile;
	FILE * pFile2;
	FILE * pFile3;
	char FullPath2[200];
	char FullPath3[200];
	int vSize;
	char * buffer;
	sCode vCodeFileHeader;
	sCode vCodeFileCpp;
	size_t result;
	bool vBoolFileName;
	int vLen;
	ZeroMemory(&FullPath,sizeof(FullPath));
	printf("%s\n","Enter the full path to the jass file : ");
	gets(FullPath);
	vLen = strlen(FullPath);
	vBoolFileName = false;
	if (vLen < 4)
	{
		printf("%s\n","The file path is too short!");
		goto m2;
	}
	if (!(FullPath[vLen-2] == '.' && FullPath[vLen-1] == 'j'))
	{
		printf("%s\n","Incorrect file extension!");
		goto m2;
	}
	for (int vvi = vLen - 1; vvi >= 0; vvi--)
	{
		if (FullPath[vvi] == '/')
		{
			if (vvi < vLen - 4 && vvi > 4)
			{
				memcpy(Path2,FullPath,vvi);
				Path2[vvi] = '\0';
				memcpy(FileName,&FullPath[vvi+1],vLen - vvi - 3);
				FileName[vLen - vvi - 3] = '\0';
				vBoolFileName = true;
			}
			break;
		}
	}
	if (vBoolFileName == false)
	{
		printf("%s\n","Error entering the file path!");
		goto m2;
	}
	//Полный путь "/etc/games/w3/war3map.j"
	//sprintf(Path2,"%s\0","/etc/games/w3");
	//sprintf(FullPath,"%s/war3map.j",Path2);
	sprintf(FullPath2,"%s/war3map.cpp",Path2);
	sprintf(FullPath3,"%s/war3map.h",Path2);
	pFile = fopen(FullPath,"rb");// открываем файл
	if (pFile==NULL)
	{
		printf("%s\n","File not found!");
		goto m2;
	}

	vSize = filelength(fileno(pFile));
	if (vSize <= 2)
	{
		printf("%s\n","The file is too small!");
		fclose(pFile);
		goto m2;
	}
	buffer = (char*) malloc(sizeof(char) * vSize); // выделить память для хранения содержимого файла

	result = fread(buffer, 1, vSize, pFile);       // считываем файл в буфер
	
	fclose(pFile);

	printf("%s\n","Loading...");
	if (fConverter(buffer,vSize) == FALSE) goto m1;

	if (vFileCpp.fOutputCode(&vCodeFileCpp) == TRUE)
	{
		pFile2 = fopen(FullPath2,"wb");// открываем файл
		if (pFile2==NULL)
			goto m1;

		result = fwrite(vCodeFileCpp.pCode,1,vCodeFileCpp.vSize,pFile2);

		fclose(pFile2);
		printf("%s\n",FullPath2);
	}

	if (vFileHeader.fOutputCode(&vCodeFileHeader) == TRUE)
	{
		pFile3 = fopen(FullPath3,"wb");// открываем файл
		if (pFile3==NULL)
			goto m1;

		result = fwrite(vCodeFileHeader.pCode,1,vCodeFileHeader.vSize,pFile3);

		fclose(pFile3);
		printf("%s\n",FullPath3);
	}
m1:;
	free(buffer);
	//printf("%s\n",FullPath);
m2:;
  getchar();
	return 0;
}

