/* Copyright 1990 by Christopher A. Wichura.
   See file GIFMachine.doc for full description of rights.
*/

#include "GIFMachine.h"

struct MinList CommentList;
static UBYTE buf[256];

BOOL DoExtension(BPTR fh)
{
	register LONG size;
	register LONG cmdcode;
	register char *Comment;
	register char *OldComment;
	register int CommentLength;
	register int OldCommentLength;
	register struct CommentNode *cn;

	if ((cmdcode = FGetC(fh)) == -1) {
		PutStr("...I/O error reading extension block function code\n");
		return TRUE;
	}

	switch(cmdcode) {
		case GIF_COMMENT_EXT:
			PutStr("...Comment extension encountered.  Contents will be stored in an ANNO chunk.\n");

			if (!(cn = (struct CommentNode *)MyAlloc(sizeof(struct CommentNode)))) {
				PutStr("......Out of memory allocating comment block.\n");
				return TRUE;
			}

			Comment = NULL;
			CommentLength = 0;

			for (;;) {
				if ((size = FGetC(fh)) == -1) {
					PutStr("......I/O Error reading comment block.\n");
					return TRUE;
				}

				if (size) {
					if (FRead(fh, buf, 1, size) != size) {
						PutStr("......I/O Error reading comment block.\n");
						return TRUE;
					}

					OldComment = Comment;
					OldCommentLength = CommentLength;
					CommentLength += size;

					if (!(Comment = MyAlloc(CommentLength))) {
						PutStr("......Out of memory allocating comment block.\n");
						return TRUE;
					}

					if (OldCommentLength) {
						CopyMem(OldComment, Comment, OldCommentLength);
						MyFree(OldComment);
					}

					CopyMem(buf, &Comment[OldCommentLength], size);
				} else {	/* end of comment so store it */
					cn->cn_Comment = Comment;
					cn->cn_CommentLength = CommentLength;
					AddTail((struct List *)&CommentList, (struct Node *)cn);
					return FALSE;
				}
			}
			break;

		default:
			MyPrintf("...Extension block function code #%ld not know, skipping.\n",
			 cmdcode);

			/* we must skip over any data for the extension block */
			for (;;) {
				if ((size = FGetC(fh)) == -1) {
					PutStr("...I/O Error skipping unknown extension block.\n");
					return TRUE;
				}

				if (size == 0)
					return FALSE;

				if (FRead(fh, buf, 1, size) != size) {
					PutStr("...I/O Error skipping unknown extension block.\n");
					return TRUE;
				}
			}
			break;
	}
}
