// ----------------------------------------
// NTRQ2NSF
// Command-line to to export NSF from NTRQ
// ----------------------------------------

#include <stdio.h>
#define nsfHeaderSize 128
#define ntrqDataSize 0x2000
#define ntrqnsfBinarySize (0x8000 + nsfHeaderSize)
#define ntrqDataOffset (ntrqDataSize + nsfHeaderSize)

int getFileSize (FILE *file)
{
	int size;
	fseek(file, 0, SEEK_END);
	size = ftell(file);
	fseek(file, 0, SEEK_SET);
	return size;
}

int main (int argc, const char * argv[]) {

	FILE *ntrqBinary;
	FILE *ntrqSave;
	FILE *nsf;
	int i;
	char buffer[ntrqnsfBinarySize];
	char ntrqBinaryName[] = "NTRQNSF.BIN";

	if (argc < 3) {
		printf("\n");
		printf("NTRQ2NSF V1.0: Convert NTRQ .sav file to NSF\n\n");
		printf("Usage : NTRQ2NSF <ntrq.sav> <output.nsf>\n\n");
		printf("- The file NTRQNSF.BIN is required. It is included with NTRQ.\n- Your .SAV file must be uncompressed (8192 bytes in size).\n");
		printf("- Some emulators use compressed .SAV files and these are not compatible with NTRQ2NSF.\n");
		printf("- The resulting .NSF will contain all 8 songs contained in the .SAV file, even some of them are empty.\n\n");
		return 0;
	}
	
	const char *inputName = argv[1];
	const char *outputName = argv[2];
	
	// Read base binary file into buffer	
	if ((ntrqBinary = fopen (ntrqBinaryName,"rb"))!=0)
	{
		if (getFileSize(ntrqBinary)!=ntrqnsfBinarySize)
		{
			printf("\nError, NTRQNSF.BIN is invalid or corrupted.\n\n");
			fclose(ntrqBinary);
			return 0;
		}
		fread(buffer, 1, sizeof(buffer), ntrqBinary);
		fclose(ntrqBinary);
	} else {
		printf("\nError, could not open NTRQNSF.BIN\n\n");
		return 0;
	}
	
	// Attempt to patch binary using .sav file
	if ((ntrqSave = fopen (inputName, "rb"))!=0)
	{
		// If .sav not 8192 bytes, .sav file probably compressed
		if (getFileSize(ntrqSave)!=ntrqDataSize)
		{
			printf("\nError, it seems that your .SAV file is compressed. Please unzip it and re-run NTRQ2NSF\n\n");
			fclose(ntrqSave);
			return 0;
		} else {
			fread (buffer+(ntrqDataOffset), 1, ntrqDataSize, ntrqSave);
			fclose(ntrqSave);
		}
	} else {
		printf("\nError, could not find specified .SAV file.\n\n");
		fclose(ntrqSave);
	}
	
	// Attempt to write output file
	if ((nsf = fopen (outputName, "wb"))!=0)
	{
		fwrite(buffer, 1, sizeof(buffer), nsf);
		fclose(nsf);
		printf("\nSuccessfully written NSF file, %s\n\n", outputName);		
	
	} else {
		printf("\nError creating output file.\n\n");
		fclose(nsf);
	}
	
	return 0;
}
