#ifndef NOPT36
#include "uade_tnplug.h"
#include <libraries/iffparse.h>

/* Code for extracting PTDT chunk from a PT 3.6 module (disabled by default
   since UADE doesn't seem to handle it anyway) */

#define ERROR_OK 0
#define ID_MODL MAKE_ID('M','O','D','L')
#define ID_PTDT MAKE_ID('P','T','D','T')

BOOL IsPT36 (uint8 *testbuffer, int32 testsize) {
	if (testbuffer && testsize >= 12) {
		if (((uint32 *)testbuffer)[0] == ID_FORM && ((uint32 *)testbuffer)[2] == ID_MODL) {
			return TRUE;
		}
	}
	return FALSE;
}

static inline CONST_STRPTR IDtoSTR (uint32 id) {
	static TEXT str[5];
	((uint32 *)str)[0] = id;
	str[4] = 0;
	return str;
}

BOOL UnpackPT36 (CONST_STRPTR infilename, CONST_STRPTR outfilename) {
	BPTR file;
	BOOL res = FALSE;
	dbug(("UnpackPT36 called.\n"));
	file = IDOS->Open(infilename, MODE_OLDFILE);
	if (file) {
		uint32 buf[3];
		if (IDOS->Read(file, buf, 12) == 12) {
			if (buf[0] == ID_FORM && buf[2] == ID_MODL) {
				int32 pt36_cludge = 12; /* workaround for buggy PT 3.6 format */
				while (IDOS->Read(file, buf, 8) == 8) {
					dbug(("Chunk ID: %08lx\n", buf[0]));
					dbug(("Chunk Size: %lu\n", buf[1]));
					if (buf[0] == ID_PTDT) {
						uint8 *outbuffer;
						int32 outsize;
						outsize = buf[1];
						outbuffer = IExec->AllocVecTags(outsize,
							AVT_Type, MEMF_SHARED,
							AVT_Lock, FALSE,
							TAG_END);
						if (outbuffer) {
							if (IDOS->Read(file, outbuffer, outsize) == outsize) {
								res = WriteFile(outfilename, outbuffer, outsize);
							}
							IExec->FreeVec(outbuffer);
						}
						break;
					} else {
						int32 skipsize;
						skipsize = buf[1] - pt36_cludge;
						pt36_cludge = 8;
						if (!IDOS->ChangeFilePosition(file, skipsize, OFFSET_CURRENT)) {
							break;
						}
					}
				}
			}
		}
		IDOS->Close(file);
	}
	return res;
}
#endif

