// ------------------------------------------------------------------
// backgbmp.cpp
// System for handling level backgrounds
// ------------------------------------------------------------------
// By Kronoman - In loving memory of my father
// Copyright (c) 2004, Kronoman
// ------------------------------------------------------------------

#include "backgbmp.h"
#include "gerror.h"
#include "filehelp.h"

CBackground::CBackground()
{
	bmp_in_ram = NULL;
	bmp_default = NULL;
	data_loaded = NULL;
	free_memory();
}

CBackground::~CBackground()
{
	free_memory();

	if (bmp_default != NULL)
		destroy_bitmap(bmp_default);
}

BITMAP *CBackground::get_background(char *filename, int index)
{
	char str[1024];
	DATAFILE *data = NULL;
	char tmp_file_buf[2048];

	where_is_the_filename(tmp_file_buf, filename);

	// use the cache if it is present
	if (index == index_loaded)
	{
		if (ustrcmp(tmp_file_buf, file_loaded) == 0)
			return bmp_in_ram;
	}

	free_memory();

	usprintf(str, "B%d_BMP", index);
	data = load_datafile_object(tmp_file_buf, str);

	if (data != NULL)
	{
		usprintf(file_loaded, "%s", tmp_file_buf);
		index_loaded = index;

		data_loaded = data;
		bmp_in_ram = (BITMAP *)data->dat;
		return bmp_in_ram;
	}


	return bmp_default;
}

void CBackground::free_memory()
{
	if (data_loaded != NULL)
		unload_datafile_object(data_loaded);

	data_loaded = NULL;

	bmp_in_ram = NULL;

	if (bmp_default != NULL)
		destroy_bitmap(bmp_default);

	bmp_default = create_bitmap(16, 16);

	if (bmp_default == NULL)
		raise_error("* FATAL ERROR * \nCBackgrounds::free_memory()\n\tCan't create default bitmap!");

	clear(bmp_default);

	file_loaded[0] = '\0';

	index_loaded = -1;
}

