/*****************************************************************************/
/****                                                                     ****/
/****  File sorgente image.c                                              ****/
/****  di Alberto Geneletti	version 1.0	giugno 1993               ****/
/****                                                                     ****/
/****  Funzioni per la creazione e la distruzione dell'oggetto            ****/
/****  PseudoColorImage, utilizzato dalle Class Libs per la codifica e la ****/
/****  decodifica dei file grafici.                                       ****/
/****  StubERR e StubNOP sono routine assegnate di default  alle due mem- ****/
/****  ber function dell'oggetto (vedi image.h).                          ****/
/*****************************************************************************/

#include <stdio.h>
#include "systems.h"
#include "image.h"


PseudoColorImage *CreatePseudoColorImage(int16 Width, int16 Height,
			int16 Depth, int16 NColors, Colormap *ColorMap,
			char huge *BitMap, void (*ShowWorkInProgress)(),
			int (*Display)())
{
	PseudoColorImage *NewImage;

	if(!(NewImage = (PseudoColorImage *)malloc(sizeof(PseudoColorImage)))) 
		return(NULL);

	NewImage->Width  		= Width;
	NewImage->Height 		= Height;
	NewImage->Depth  		= Depth;
	NewImage->AllocationFlags 	= NOTHING_AUTOALLOCATED;
	NewImage->NColors 		= NColors;

	if(ColorMap) 
			NewImage->ColorMap = ColorMap;
	else 
		if(NColors != 0) {
			NewImage->ColorMap = (Colormap *)malloc(sizeof(ColorMap));
                        if(!NewImage->ColorMap) {
				DestroyImage(NewImage);
				return(NULL);
                        }
			else
				NewImage->AllocationFlags |= AUTOALLOCATED_CMAP;
         	}
		else
			NewImage->ColorMap = NULL;



	 if(BitMap)
		NewImage->BitMap = BitMap;
		else {
                	if((Width != 0) && (Height != 0)) {
				NewImage->BitMap = (char huge *)
					farmalloc((long)NewImage->Width*(long)NewImage->Height);
                                if(!NewImage->BitMap) {
                                	DestroyImage(NewImage);
					return(NULL);
                                }
				else
					NewImage->AllocationFlags |= AUTOALLOCATED_BITMAP;
                        }
			else
				NewImage->BitMap = NULL;
                }

	if(Display)
		NewImage->Display = Display;
	else
		NewImage->Display = StubERR;

	if(ShowWorkInProgress)
		NewImage->ShowWorkInProgress = ShowWorkInProgress;
	else
		NewImage->ShowWorkInProgress = StubNOP;

return(NewImage);
}

void DestroyImage(PseudoColorImage *Im)
{
	if(!Im)
		return;

	if(Im->AllocationFlags & AUTOALLOCATED_CMAP) 
		free(Im->ColorMap);
	
	if(Im->AllocationFlags & AUTOALLOCATED_BITMAP) 
		farfree(Im->BitMap);

	free(Im);
}


int StubERR()
{
	printf("I don\'t know how to Display the Image.");
	return(-1);
}

void StubNOP(int Error, PseudoColorImage* Im)
{
}
