#include "ma_moor3.h"

char *CMassMoor3::GetIdent( void )
{
	static char Ident[] = "DAT (Moorhuhn3)b";

	return Ident;
}

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

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

	char	buf[ 100 ];
	fseek( massf, 0, SEEK_SET );
	fread( buf, 12, 1, massf );

	if ( strcmp( buf, "MH3 V1.0 " ) == 0 )
		return 1;
	else
		return 0;
}

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

	if ( massf == NULL )
		return;

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

	fseek( massf, 0, SEEK_SET );
	lib_start = SizeOfMoor3Rec;
	files_count = 0;
	fread( &moor3Rec, SizeOfMoor3Rec, 1, massf );
	data_start = moor3Rec.offset;
	do {
		if ( fread( &moor3Rec, SizeOfMoor3Rec, 1, massf ) != 1 )
			break;
		files_count++;
	} while (( strcmp( moor3Rec.name, "****" ) != 0 ) &&
			 ( (unsigned long)ftell( massf ) < data_start ));
	files_count--;
}

int	 CMassMoor3::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 ) );

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

	//read
	if ( fread( &moor3Rec, SizeOfMoor3Rec, 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
	FileRec.SetName( moor3Rec.name );
	FileRec.offset 	= moor3Rec.offset;
	FileRec.size    = moor3Rec.size;

	return 1;
}

