/* animcontrol.c
 *
 *      functions for animation file manipulation
 *
 * This routine provided for the GrabAnim program by
 * Gary Bonham, SPARTA, Inc., Laguna Hills.
 *
 * This is also intended to serve as an example of how to
 * generate ANIM files.
 *
 */

#include <intuition/intuitionbase.h>
#include <graphics/gfxbase.h>
#include <dos/dosextens.h>
#include <exec/memory.h>

#include <iff/iff.h>
#include <iff/ilbm.h>
#include <iff/readpict.h>

extern struct BitMap *mybitmap[];

static LONG	 fil;
static UBYTE	*buffer;
static LONG	 Width,Height,Depth;

BYTE	OpenAnimationFile(LONG nbuf,UBYTE *cc,struct ColorMap *cm,struct ViewPort *vp);
BYTE	AddAnimationFrame(LONG nbuf);
BYTE	AddAnimationFrame2(LONG *data,LONG ndata,LONG pop);

VOID	CloseAnimationFile(VOID);

BOOL	OpenAnim(LONG file,struct BitMap *bm,WORD pageW,WORD pageH,WORD *colorMap,ULONG modes,BYTE *buffer,LONG bufsize);
BOOL	AddAnim(struct BitMap *bm,WORD pageW,WORD pageH,WORD pop,BYTE *buffer,LONG bufsize);
BOOL	AddAnim2(LONG *data,LONG ndata,LONG pop);
BOOL	CloseAnim(LONG file);

/* =================================================== */

BYTE
OpenAnimationFile(LONG nbuf,UBYTE *cc,struct ColorMap *cm,struct ViewPort *vp)
{
	if(fil = Open(cc,MODE_NEWFILE))
	{
		if(buffer = (UBYTE *)AllocMem(16000,MEMF_CHIP|MEMF_CLEAR))
		{
			Width	= mybitmap[nbuf] -> BytesPerRow << 3;
			Height	= mybitmap[nbuf] -> Rows;

			if(OpenAnim(fil,mybitmap[nbuf],Width,Height,cm -> ColorTable,GetVPModeID(vp),buffer,16000))
				return(TRUE);

			FreeMem(buffer,16000);

			buffer = NULL;
		}

		Close(fil);

		fil = NULL;

		DeleteFile(cc);
	}

	return(FALSE);
}

BYTE
AddAnimationFrame(LONG nbuf)
{
	Width	= mybitmap[nbuf] -> BytesPerRow << 3;
	Height	= mybitmap[nbuf] -> Rows;

	if(AddAnim(mybitmap[nbuf],Width,Height,1,buffer,16000))
		return(TRUE);
	else
		return(FALSE);
}

BYTE
AddAnimationFrame2(LONG *data,LONG ndata,LONG pop)
{
	if(AddAnim2(data,ndata,pop))
		return(TRUE);
	else
		return(FALSE);
}

VOID
CloseAnimationFile()
{
	if(fil)
	{
		UBYTE Name[256];

		CloseAnim(fil);

		if(NameFromFH(fil,Name,256))
		{
			BPTR FileLock;

			Close(fil);

			if(FileLock = Lock(Name,ACCESS_READ))
			{
				struct FileInfoBlock __aligned FIB;

				if(Examine(FileLock,&FIB))
				{
					UnLock(FileLock);

					if(!FIB . fib_Size)
						DeleteFile(Name);
					else
						SetProtection(Name,FIBF_EXECUTE);
				}
				else
					UnLock(FileLock);
			}
		}
		else
			Close(fil);

		fil = NULL;
	}

	if(buffer)
	{
		FreeMem(buffer,16000);

		buffer = NULL;
	}
}
