#include "ma_lbx.h"

char *CMassLbx::GetIdent( void )
{
	static char Ident[] = "LBX (Gainax)";

	return Ident;
}

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

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

	if ( strcmp( MassFileExt, "lbx" ) == 0 )
		return 1;

	return 0;
}

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

	if ( massf == NULL )
		return;

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

	unsigned short	s;

	fseek( massf, filesize - 6, SEEK_SET );
	fread( &s, 2, 1, massf );
	files_count = s;
	fread( &lib_start, 4, 1, massf );
}

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

	//read
	if ( fread( &lbxRec, SizeOfLbxRec, 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
	int		i;

	memcpy( FileRec.name, lbxRec.name, lbxNameLen );
	i = lbxNameLen - 1;
	while ( FileRec.name[ i ] == '\x20' )
		i--;
	FileRec.name[ i + 1 ] = '\0';
	FileRec.offset = lbxRec.offset;
	FileRec.size   = lbxRec.size;

	return 1;
}

