#include "ma_vf1bi.h"

char *CMassVF1bin::GetIdent( void )
{
	static char Ident[] = "BIN (Virtua Fighter 1 bitmaps)";

	return Ident;
}

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

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

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

	if ( memcmp( buf, "BM", 2 ) == 0 )
		return 1;
	else
		return 0;
}

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

	if ( massf == NULL )
		return;

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

	unsigned long	p, s, i, e;

	files_count = 0;

	fseek( massf, 0, SEEK_SET );
	p = 0; s = BufSize; i = 0;

	do {
		if ( p + s > filesize )
			s = filesize - p;
		
		fread( &buffer[ i ], s, 1, massf );
		e = i + s;

		while ( i < e - 1 ) {
			if (( buffer[ i ] == 'B' ) && ( buffer[ i + 1 ] == 'M' ))
				files_count++;
			i++;
		}

		buffer[ 0 ] = buffer[ i ];
		i = 1;

		p += s;
	} while ( p < filesize );
}

int	 CMassVF1bin::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;

	unsigned long	p, s, i, e, b, fofs, nextofs;

	//seek
	if ( num == -1 ) {
		p = next_rec_pos;

		num = next_rec_num;
		pos = next_rec_num;
	}
	else {
		p = 0;
		pos = 0;
	}

	// read
	fseek( massf, p, SEEK_SET );
	s = BufSize; i = 0;

	fofs = nextofs = -1; 
	do {
		if ( p + s > filesize )
			s = filesize - p;
		
		fread( &buffer[ i ], s, 1, massf );
		e = i + s;

		b = i; i = 0;
		while (( e > 0 ) && ( i < e - 1 )) {
			if (( buffer[ i ] == 'B' ) && ( buffer[ i + 1 ] == 'M' )) {
				pos++;

				if ( pos == num + 1 ) {
					fofs = p + i - b;
				}
				if ( pos == num + 2 ) {
					nextofs = p + i - b;
					i = e - 1;
					p = filesize;
					break;
				}
			}

			i++;
		}

		buffer[ 0 ] = buffer[ i ];
		i = 1;

		p += s;
	} while ( p < filesize );

	if ( fofs == -1 )
		fofs = 0;
	if ( nextofs == -1 )
		nextofs = filesize;

	//set position of the next
	next_rec_pos = nextofs;
	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
	sprintf( FileRec.name, "file%04lu.bmp", num );
	FileRec.offset = fofs;
	FileRec.size = nextofs - fofs;
	FileRec.set = 1;

	return 1;
}
