// ------------------------------------------------------------------
// musiclvl.cpp
// System for handling level's music
// ------------------------------------------------------------------
// By Kronoman - In loving memory of my father
// Copyright (c) 2004, Kronoman
// ------------------------------------------------------------------

#include <allegro.h>
#include <dumb.h>

#include "musiclvl.h"
#include "gerror.h"
#include "filehelp.h"

CMusicLvl::CMusicLvl()
{
	music_in_ram = NULL;
	data_loaded = NULL;
	free_memory();
}

CMusicLvl::~CMusicLvl()
{
	free_memory();
}


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

	data_loaded = NULL;

	music_in_ram = NULL;

	file_loaded[0] = '\0';

	index_loaded = -1;
}

DUH *CMusicLvl::get_music(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 music_in_ram;
	}

	free_memory();

	usprintf(str, "M%d_XM", 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;
		music_in_ram = (DUH *)data->dat;
		
		return music_in_ram; // found OK
	}


	return NULL; // not found
}
