#include <exec/types.h>
#include <exec/memory.h>
#include <exec/libraries.h>
#include <intuition/intuition.h>

#include "personal_io.h"
#define GRAPHICS_BASE_NAME picinfo->GfxBase
#define EXEC_BASE_NAME picinfo->SysBase
#include <inline/graphics.h>
#include <inline/exec.h>

/*
 *  This function copies a "black box" 8-bit bitmap
 *  to a standard bitmap
 */

BOOL CopyBitMap8(struct BitMap *src,
			struct BitMap *dst,
			WORD width,
			WORD height,
			struct PictureInfo *picinfo)
{
	register struct BitMap *temp_bm;
	struct RastPort rport, temp_rp;
	register UBYTE *pixbuff, *pb;
	register WORD x, y;
	LONG rowsize, offs;
	BOOL ok = FALSE;

	if (picinfo->GfxBase->lib_Version >= 39)
		temp_bm = AllocBitMap(width, 1, picinfo->Depth, BMF_CLEAR, NULL);   /* temp bitmap for ReadPixelLine8() */
	else
	{
		WORD i,j,d=picinfo->Depth;
		UBYTE *planes;

		temp_bm = AllocVec(sizeof(struct BitMap), MEMF_PUBLIC| MEMF_CLEAR);
		InitBitMap(temp_bm, d, width, 1);

		j=temp_bm->BytesPerRow; /* RASSIZE */
		planes = AllocVec(j*d, MEMF_CHIP| MEMF_PUBLIC| MEMF_CLEAR);
		for(i=0;i<d;i++) temp_bm->Planes[i] = planes[j*i];
	}
	if(temp_bm)
	{
		rowsize = ((width + 15) >> 4) << 4;
		if (pixbuff = AllocMem(rowsize, 0))
		{
			ok = TRUE;
			InitRastPort(&rport);
			rport.BitMap = src;
			InitRastPort(&temp_rp);
			temp_rp.BitMap = temp_bm;

			for (y = 0; y < height; y++)
			{
				ReadPixelLine8(&rport, 0, y, width, pixbuff, &temp_rp);
				pb = pixbuff;
				if ((width & 31) == 0)  /* fast (aligned) copy */
				{
					offs = dst->BytesPerRow * y;
					for (x = width >> 5; --x >= 0; pb += 32, offs += 4)
						picinfo->ChunkyToBMap(pb, dst, offs);
				}
				else	/* normal copy */
				{
					picinfo->FastWritePix(dst, FBMP_INIT,0,0);
					for (x = 0; x < width; x++)
						picinfo->FastWritePix(dst, x, y, *pb++);

					picinfo->FastWritePix(dst, FBMP_FLUSH,0,0);
				}
			}
			FreeMem(pixbuff, rowsize);
		}
		if(picinfo->GfxBase->lib_Version >= 39)
			FreeBitMap(temp_bm);
		else
		{
			FreeVec(temp_bm->Planes[0]);
			FreeVec(temp_bm);
		}
	}
	return(ok);
}

