#include <datatypes/datatypes.h>
#include <exec/memory.h>

#include <clib/dos_protos.h>
#include <clib/exec_protos.h>

#include <pragmas/dos_pragmas.h>
#include <pragmas/exec_sysbase_pragmas.h>

#define DOSBase          dthc->dthc_DOSBase
#define SysBase          dthc->dthc_SysBase

BOOL __interrupt __asm DTHook (register __a0 struct DTHookContext * dthc)
{
	BOOL retval = FALSE;
	UBYTE *buffer;
	BPTR fh;
	UWORD width,height;
	ULONG filesize;

	if (							/* Make sure we have: */
		(fh = dthc->dthc_FileHandle) &&			/* a FileHandle */
		dthc->dthc_FIB &&				/* a FileInfoBlock */
		(buffer = dthc->dthc_Buffer) &&			/* a Buffer */
		(dthc->dthc_BufferLength >= 4) &&		/* width and height in buffer */
		(width = (buffer[1] << 8) + buffer[0]) &&	/* width != 0 */
		(height = (buffer[3] << 8) + buffer[2]) &&	/* height != 0 */
		(filesize = 4			/* width + height */
			+ (height << 1)		/* linenumbers */
			+ (width * height * 3) /* 24 Bits per pixel */
		) == dthc->dthc_FIB->fib_Size			/* and the correct length of the file */
	   )
	{
		ULONG linesize = width * 3 + 2;
		UWORD i;

		Seek(fh, 0, OFFSET_BEGINNING);	/* avoid bug in datatypes.library 40.6 */
		/* Allocate a buffer and skip width and height */
		if((buffer = AllocVec(linesize, MEMF_PUBLIC)) && (Read(fh, buffer, 4) == 4))
		{
			for (i = 0, retval = TRUE; (i < height) && (retval == TRUE); i++)
			{
				if (
					(Read(fh, buffer, linesize) != linesize) ||	/* file can be read */
					(i != ((buffer[1] << 8) + buffer[0]))		/* linenumber check */
				   )
					retval = FALSE;
			}
			FreeVec(buffer);
		}
	}
	return retval;
}
