/* ======================================================================== *
	   readcliptext.c - Subroutines to read and write text to the clipboard
							       By Talin.
				  Compiled under Manx 5.0 with small code/data
 * ======================================================================== */

#include <std_headers.h>
#include <libraries/iffparse.h>

extern struct Library *IFFParseBase;

#define LEAVE	goto exitit

int ReadClipText(char *text, int maxlength)
{	struct IFFHandle	*iff = NULL;
	long				result = FALSE;

	unless (iff = AllocIFF()) { result = -100; LEAVE; }
	unless (iff->iff_Stream = (ULONG) OpenClipboard (PRIMARY_CLIP))
	{	result = -101; LEAVE; }
	InitIFFasClip (iff);

	if (result = OpenIFF (iff, IFFF_READ)) LEAVE;
	if (result = StopChunk (iff, 'FTXT', 'CHRS')) LEAVE;

	while (maxlength > 0)
	{	long error; 

		error = ParseIFF (iff, IFFPARSE_SCAN);

		if (error == IFFERR_EOF) LEAVE;
		if ((result = ReadChunkBytes (iff, (APTR)text, maxlength)) <= 0)
			LEAVE;
		text += result;
		maxlength -= result;
	}

exitit:
	if (iff)
	{	CloseIFF (iff);
		if (iff->iff_Stream)
			CloseClipboard ((struct ClipboardHandle *)iff->iff_Stream);
		FreeIFF (iff);
	}
	return result;
}
