#include <Global.h>
// Author: Nicolas Livaditis (NightWolve)
// Purpose: For PC Engine CD Dubbing projects (Ys IV, Popful Mail)
// Version: 10/16/2025

BOOL IsMatch(PBYTE lpBuffer);

#define FILECODE "PMAIL_"
char GetFile[] = FILECODE"GET_VOX_FROM_ISO.bat";
char PutFile[] = FILECODE"PUT_VOX_INTO_ISO.bat";

char FIND_ISO_CMD[] = "@FileBySize *.iso 82313216 /set=ISO > out.bat\r\n@call out.bat\r\n@del out.bat\r\n@IF EXIST %%ISO%% GOTO BEGIN\r\n@FOR /F %%%%I IN ( 'FileBySize *.iso 82313216 /s' ) DO SET ISO=\"%%%%I\"\r\n:BEGIN\r\n\r\n";

// ** Ys IV ADPCM Offset Range
// ADPCMFinder ys4.iso 0x2001000 0x3EE4800
// char ADPCMBREAK[] = "\x88\x88\x88\x88\x88\x88\x88\x88\x88\x88\x88\x88\x88\x88\x88\x88\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";

// ** Popful Mail ADPCM Offset Range
// ADPCMFinder popfulmail.iso 0x01329000 0x04E35000

int __cdecl main(int argc, char **argv) {
	DWORD StartOffset, EndOffset, ID, i, j;
	MAPPEDFILE mFile;
	PBYTE filedata;

	cls();
	if ( argc != 4 ) {
		printf("Invalid number of parameters : %d\r\n"\
		"Usage: ADPCMFinder <filein> <startoffset> <endoffset>\r\n", argc);
		return 0;
	}
	StartOffset = StringToNumber(argv[2]);
	EndOffset = StringToNumber(argv[3]);
	if ( !EndOffset ) {
		printf("Problem understanding end offset %s\r\n", argv[3]);
		return 0;
	}
	if ( !MapFile32(argv[1], FALSE, &mFile) ) {
		PrintLastSysError("Error: Can't open %s", argv[1]);
		return 0;
	}
	DeleteFileA(GetFile);
	DeleteFileA(PutFile);
	FastLog(GetFile, FIND_ISO_CMD, argv[1]);
	FastLog(PutFile, FIND_ISO_CMD, argv[1]);	
	filedata = mFile.lpMapAddress + StartOffset;
	for ( ID = 0, i = j = StartOffset; j < EndOffset; ) {
		j += 2048;
		filedata += 2048;
		if ( IsMatch(filedata) ) {
			ID++;
		// Make "GET_VOX_FROM_ISO.bat"
			FastLog(GetFile, "@FileGet %%ISO%% 0x%.7X %7lu "FILECODE"%.3d_%.7X.vox\r\n", i, (j-i), ID, i);
		// Make "PUT_VOX_INTO_ISO.bat"
			FastLog(PutFile, "@IF EXIST "FILECODE"%.3d_%.7X.vox FilePut %%ISO%% "FILECODE"%.3d_%.7X.vox 0x%.7X 0 0\r\n", ID, i, ID, i, i);
			i = j;
		}
	}
	CloseMap(mFile);
	return 0;
}

BOOL IsMatch(PBYTE lpBuffer) {
	DWORD Count;
	lpBuffer--;
	Count = 0;
	for ( ; *lpBuffer == 0x08; lpBuffer-- ) {
		Count++;
		if ( Count == 32 )
			return TRUE;
	}
	if ( Count )
		return FALSE;
	for ( ; *lpBuffer == 0x00; lpBuffer-- ) {
		Count++;
		if ( Count == 32 )
			return TRUE;
	}
	return FALSE;
}
