#include "ma_eth2.h"

char *CMassEth2::GetIdent( void )
{
	static char Ident[] = "RES (Etherlords2)";

	return Ident;
}

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

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

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

	return ( memcmp( buf, "\x3C\xE2\x9C\x01", 4 ) == 0 );
}

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

	if ( massf == NULL )
		return;

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

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

	lib_size = files_count * SizeOfEth2Rec;
}

int	 CMassEth2::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 = lib_start + SizeOfEth2Rec * num;
		if ( fseek( massf, pos, SEEK_SET ) != 0 )
			return 0;
	}

	//read
	if ( fread( &Eth2Rec, SizeOfEth2Rec, 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.offset	= Eth2Rec.offset;
	FileRec.size	= Eth2Rec.size;
	//nacitam meno
	if ( fseek( massf, lib_start + lib_size + Eth2Rec.nameoffset, SEEK_SET ) != 0 )
		return 0;
	fread( FileRec.name, 1, Eth2Rec.namelen, massf );
	FileRec.name[ Eth2Rec.namelen ] = 0;
	FileRec.set = 1;

	return 1;
}
