#include <libraries/iffparse.h>

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

#include <pragmas/dos_pragmas.h>
#include <pragmas/exec_pragmas.h>
#include <pragmas/iffparse_pragmas.h>
#include<pragmas/locale_pragmas.h>

#define ID_FTXT MAKE_ID('F','T','X','T')
#define ID_CHRS MAKE_ID('C','H','R','S')

extern struct Library *DOSBase, *SysBase;
struct Library *IFFParseBase = NULL;
struct IFFHandle *Iff = NULL;

BOOL init_iffparse( void )
{
	if ( ( IFFParseBase = OpenLibrary( "iffparse.library", 37L ) ) != NULL )
	{
		if ( (Iff = AllocIFF() ) != NULL )
		{
			if ( ( Iff->iff_Stream = (ULONG)OpenClipboard( 0 ) ) != NULL )
			{
				InitIFFasClip( Iff );
				return TRUE;
			}
		}
	}
  return FALSE;
}

void close_iffparse( void )
{
	if ( Iff != NULL  &&  Iff->iff_Stream != NULL )
		CloseClipboard( (void *)Iff->iff_Stream );

	if ( Iff != NULL ) FreeIFF( Iff );

	if ( IFFParseBase != NULL ) CloseLibrary( IFFParseBase );
}

ULONG read_clip( UBYTE *buffer, ULONG buflen )
{
	struct ContextNode  *cn;
	ULONG length = 0;

	OpenIFF( Iff, IFFF_READ );
	if ( StopChunk( Iff, ID_FTXT, ID_CHRS ) == 0 )
	{
		while ( ParseIFF( Iff, IFFPARSE_SCAN ) == 0 )
		{
			cn = CurrentChunk( Iff );

			if ( ( cn ) && ( cn->cn_Type == ID_FTXT ) && ( cn->cn_ID == ID_CHRS ) )
			{
				length = ReadChunkBytes( Iff, buffer, buflen );
				break;
			}
		}
	}

	CloseIFF( Iff );
	return length;
}

void write_clip( UBYTE *data, ULONG length )
{
	OpenIFF( Iff, IFFF_WRITE );

	if ( PushChunk( Iff, ID_FTXT, ID_FORM, IFFSIZE_UNKNOWN ) == 0 )
	{
		if ( PushChunk( Iff, 0, ID_CHRS, IFFSIZE_UNKNOWN ) == 0 )
		{
			WriteChunkBytes( Iff, data, length );
			PopChunk( Iff );
		}
		PopChunk (Iff);
	}
	CloseIFF( Iff );
}
