#include "ma_mgmnl.h"

char *CMassMegamanLegendsWB::GetIdent( void )
{
	static char Ident[] = "WB(Megaman Legends)";

	return Ident;
}

char *CMassMegamanLegendsWB::GetExtension( void )
{
	static char Ext[] = "WB";
	return Ext;
}

int	 CMassMegamanLegendsWB::CheckFileType( void )
{
	if ( massf == NULL )
		return 0;

	unsigned long	ul;
	
	fseek( massf, 0, SEEK_SET );
	fread( &ul, 4, 1, massf );
	fseek( massf, ul - 4, SEEK_SET );
	fread( &ul, 4, 1, massf );
	fseek( massf, 0, SEEK_END );
	if ( ul == (unsigned)ftell( massf ) )
		return 1;
	else
		return 0;
}

void CMassMegamanLegendsWB::GetFileMainInfo( void )
{
	files_count = 0;

	if ( massf == NULL )
		return;

	fseek( massf, 0, SEEK_END );
	filesize = ftell( massf );

	unsigned long	ul;

	fseek( massf, 0, SEEK_SET );
	fread( &ul, 4, 1, massf );
	files_count = ul / 4 - 1;
	lib_start = 0;
}

int	 CMassMegamanLegendsWB::ReadRec( long num )
{
	if ( massf == NULL ) 
		return 0;
	if (( (unsigned long)num >= files_count ) && ( num != -1 ))
		return 0;
	if (( num == -1 ) && 
		(( ! next_set ) || ((unsigned long)next_rec_num >= files_count )) )
		return 0;
	
	memset( &FileRec, 0, sizeof( FileRec ) );

	if (( next_set ) && ( (signed)next_rec_num == num ))
		num = -1;

	//seek
	if ( num == -1 ) {
		if ( fseek( massf, next_rec_pos, SEEK_SET ) != 0 )
			return 0;
	}
	else {
		pos = 4 * num;
		if ( fseek( massf, pos, SEEK_SET ) != 0 )
			return 0;
	}

	//read
	if ( fread( &l, 4, 1, massf ) != 1 )
		return 0;

	//set position of the next
	next_rec_pos = ftell( massf );
	if ( num == -1 )
		next_rec_num ++;
	else
		next_rec_num = num + 1;
	if ( num + 1 >= (long)files_count )
		next_set = false;
	else
		next_set = true;
	
	//get info
	if ( fread( &l2, 4, 1, massf ) != 1 )
		return 0;
	FileRec.offset = l;
	FileRec.size = l2 - l;
	sprintf( FileRec.name, "%03lu-file.", next_rec_num - 1 );

	if ( fseek( massf, l, SEEK_SET ) != 0 )
		return 0;

	if ( fread( buf, 16, 1, massf ) != 1 )
		return 0;

	if (( memcmp( buf, "RIFF", 4 ) == 0 ) && ( memcmp( &buf[8], "WAVE", 4 ) == 0 ))
		strcat( FileRec.name, "wav" );
	else {
		buf[ 2 ] = 0;
		strcat( FileRec.name, buf );
	}

	FileRec.set = 1;

	return 1;
}
