#include <exec/types.h>
#include <exec/memory.h>
#include <intuition/intuition.h>
#include <functions.h>
#include "pdefines.h"
#include "globals.h"

/* This structure makes it easy to allocate both a RastPort and a BitMap
   structure at the same time and deal with both of them. */
struct MyRast {
	struct RastPort RastPort;
	struct BitMap	BitMap;
};

/* This routine creates a RastPort and associated BitMap structure of the
    requested size and it also allocates the memory for the drawing area
    (graphics memory) */
struct RastPort *CreateRastPort (depth, width, height)
int depth, width, height;
{
	struct MyRast *mr;
	int i;

/* Allocate Memory for a MyRasy structure */
	if (( mr = AllocMem (sizeof (struct MyRast), MEMF_CLEAR)) == NULL) {
		SYSMESS ("Couldn't allocate an MyRast");
		return (NULL);
	}

/* Set the RastPort to standard values */
	InitRastPort (mr);

/* Attach the BitMap to the RastPort */
	mr->RastPort.BitMap = &mr->BitMap;

/* Setup the BitMap to values appropriate for the requested size of the
   graphic area. */
	InitBitMap (&mr->BitMap, depth, width, height);

/* Now allocate the actual graphic memory for this RastPort one plane
   at a time. */
	for (i=0; i<depth; i++) {
		if (( mr->BitMap.Planes[i] = AllocRaster (width, height)) == NULL) {
			DeleteRastPort (mr);
			SYSMESS ("Couldn't allocate memory for front Bitmap");
			return (NULL);
		}
	}

/* Clear the graphic memory */
	SetRast (mr, 0L);

/* Return the address of this new RastPort to the caller */
	return ((struct RastPort *)mr);
}

/* This routine will deallocate ONLY a rastport allocated by the above
   routine 'CreateRastPort'.  DO NOT pass it any other rastports. */
DeleteRastPort (mr)
struct MyRast *mr;
{
	int i;

	if (mr) {
		for (i=0; i<mr->BitMap.Depth; i++) {
			if (mr->BitMap.Planes[i]) {
				FreeMem (mr->BitMap.Planes[i],
				 mr->BitMap.BytesPerRow * mr->BitMap.Rows);
			}
		}
		FreeMem (mr, sizeof (struct MyRast));
	}
}

