#include "ma_pbo.h"

char *CMassPbo::GetIdent( void )
{
	static char Ident[] = "PBO (Flashpoint)b";

	return Ident;
}

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

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

	unsigned char	uc;
	unsigned long	ul;

//	if ( strlen( MassFileName ) < 4 )
//		return 0;

	if ( strcmp( MassFileExt, "pbo" ) == 0 ) {
		fseek( massf, 0, SEEK_SET );
		do {
			fread( &uc, 1, 1, massf );
		} while ( uc != 0 );
		ul = 0;
		do {
			fread( &uc, 1, 1, massf );
			if ( uc == 0 )
				ul++;
		} while (( uc == 0 ) && ( ul < 12 ));

		if ( ul == 12 )
			return 1;
	}

	return 0;
}

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

	if ( massf == NULL )
		return;

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

	unsigned char		uc;

	lib_start = 0;
	fseek( massf, 0, SEEK_SET );
	do {
		do {
			fread( &uc, 1, 1, massf );
		} while ( uc != 0 );
		if ( fread( &pboRec.u[0], 20, 1, massf ) != 1 )
			return;
		files_count++;
	} while (( pboRec.u2 != 0 ) || ( pboRec.size != 0 ));
	files_count--;
	data_start = ftell( massf );
}

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

	unsigned long		ofs, i;
	unsigned char		uc;

	//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 {
		pos = 0;
		fseek( massf, lib_start, SEEK_SET );
	}	
	//(find and ) read record

	ofs = data_start; pboRec.size = 0;
	do {
		ofs += pboRec.size;
		i = 0;
		do {
			fread( &uc, 1, 1, massf );
			if ( i < pboNameLen-1 )
				pboRec.name[ i++ ] = uc;
		} while ( uc != 0 );
		pboRec.name[ i ] = 0;

		if ( fread( &pboRec.u[0], 20, 1, massf ) != 1 )
			return 0;
		pos++;
	} while ( pos <= (unsigned long)num );

	if ( fseek( massf, pos, SEEK_SET ) != 0 )
		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( pboRec.name );
	FileRec.offset	= ofs;
	FileRec.size	= pboRec.size;

	return 1;
}

