/**	AllocRastPort.c
  *
  *	Implement the Amiga RasterPort access functions for rexxarplib.library.
  *
  *   AUTHOR/DATE:  W.G.J. Langeveld, November 1987.
  *   ============
  *
  *	CURRENT VERSION:
  *
  *	This version has been converted to SAS C 6.5 format. It has been modified
  *	for modern definition sequences for ANSI compilation. This no longer works
  *	with OS versions prior to 2.04.
  *
  *   AUTHOR/DATE:  Joanne Dow, jdow@bix.com, June 1998.
  *   ============
  *
  **/
#include <functions.h>
#include "ralprotos.h"
#include <exec/types.h>
#include <exec/exec.h>
#include <libraries/dos.h>
#include <intuition/intuition.h>
#include <graphics/gfx.h>
#include <graphics/gfxmacros.h>
#include <devices/timer.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define BMSIZE ((long) sizeof(struct BitMap))
#define RPSIZE ((long) sizeof(struct RastPort))
	
struct RastPort *AllocRastPort( int depth, int width, int height )
{
	int i;
	
	struct BitMap *b = NULL;
	struct RastPort *rp = NULL;
	
	b = (struct BitMap *) AllocMem(BMSIZE, MEMF_CLEAR|MEMF_CHIP);
	if (b == NULL)
		return(NULL);
	
	rp = (struct RastPort *) AllocMem(RPSIZE, MEMF_CLEAR);
	if (rp == NULL)
		goto cleanup;
	
	if (width & 0x7)
		width = (width & 0xFFF8) + 8;
	
	InitBitMap(b, (long) depth, (long) width, (long) height);
	for (i = 0; i < depth; i++) 
	{
		b->Planes[i] = (PLANEPTR) AllocRaster((long) width, (long) height);
		if (b->Planes[i] == NULL)
			goto cleanup;
	}
	
	InitRastPort(rp);
	rp->BitMap = b;
	
	return(rp);
	
	cleanup:
	if (b) 
	{
		width = b->BytesPerRow << 3;
		height = b->Rows;
		for (i = 0; i < depth; i++)
		if (b->Planes[i])
			FreeRaster(b->Planes[i], (long) width, (long) height);
		FreeMem(b, BMSIZE);
	}
	if (rp)
		FreeMem(rp, RPSIZE);
	
	return(NULL);
}


struct RastPort *FreeRastPort( struct RastPort *rp )
{
	int width, height, i;
	struct BitMap *b;
	
	if (rp == NULL)
		return(NULL);
	
	if (b = rp->BitMap) 
	{
		width = b->BytesPerRow << 3;
		height = b->Rows;
		for (i = 0; i < (int) b->Depth; i++)
		if (b->Planes[i])
			FreeRaster(b->Planes[i], (long) width, (long) height);
		FreeMem(b, BMSIZE);
	}
	FreeMem(rp, RPSIZE);
	
	return(NULL);
}
