#include "ma_mgs.h"
#include "utools.h"

char *CMassMgs::GetIdent( void )
{
	static char Ident[] = "DAR (Metal Gear Solid)";

	return Ident;
}

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

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

	if ( UnmassTools::_strcasecmp( MassFileExt, "dar" ) == 0 )
		return 1;
	else
		return 0;
}

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

	if ( massf == NULL )
		return;

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

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

int	 CMassMgs::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;
		pos = next_rec_num - 1;
		num = next_rec_num;
	}
	else {
		fseek( massf, lib_start, SEEK_SET );
		pos = 0;
	}

	//read
	do {
		//skip leading zeroes
		i = ( ftell( massf ) % 4 ) - 1;
		do {
			fread( &uc, 1, 1, massf );
			i++;
		} while ( uc == 0 );

		p = 0;
		do {
			if ( p < FileNameWithPathMaxLen )
				MgsRec.name[ p ] = uc;

			fread( &uc, 1, 1, massf );
			p++; i++;
		} while (( uc != 0 ) || ( (i+1) % 4 != 0 ));
		MgsRec.name[ p ] = 0;

		fread( &MgsRec.size, 4, 1, massf );	
		MgsRec.offset = ftell( massf );

		fseek( massf, MgsRec.size, SEEK_CUR );
		
		pos++;
	} while ( pos < (unsigned long)num );

	//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
	FileRec.SetName( MgsRec.name );
	FileRec.offset = MgsRec.offset;
	FileRec.size = MgsRec.size;
	FileRec.set = 1;

	return 1;
}
