#include "ma_vol.h"

char *CMassVol::GetIdent( void )
{
	static char Ident[] = "VOL (Megatech)";

	return Ident;
}

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

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

	return ( strcmp( MassFileExt, "vol" ) == 0 );
}

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

	if ( massf == NULL )
		return;

	unsigned long	ofs, vol_c, vol_i, ofs2;

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

	fseek( massf, 0, SEEK_SET );
	lib_start = 0;
	fread( &ofs, 4, 1, massf );
	if ( ofs % 0x10 != 0 )
		return;

	vol_c = ofs / 4;
	//file is added after ofs change, first ofs does not count
	//last offset is not file, it is eof
	for( vol_i=1; vol_i<vol_c; vol_i++ ) {
		fread( &ofs2, 4, 1, massf );
		//error check, ofs ! < ofs2
		if (( ofs2 < ofs ) && ( ofs2 != 0 )) {
			files_count = 0;
			return;
		}
		//move offset
		if ( ofs2 != ofs ) {
			//if there was 0, it is end of offsets, so no more offsets
			if ( ofs == 0 ) {
				files_count = 0;
				return;
			}
			ofs = ofs2;
			files_count++;
		};
		if ( ofs > filesize ) {
			files_count = 0;
			return;
		}			
	}
	files_count--;
}

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

		num = next_rec_num;
		pos = next_rec_num - 1;
	}
	else {
		if ( fseek( massf, lib_start, SEEK_SET ) != 0 )
			return 0;
		pos = 0;
	}

	unsigned long	ofs, ofs2;

	//seek and read 
	ofs = 0;
	if ( fread( &ofs2, 4, 1, massf ) != 1 )
		return 0;
	while ( 1 ) {
		if ( ofs != ofs2 ) {
			ofs = ofs2;
			//skip same offsets, will be used further
			while ( ofs == ofs2 )
				fread( &ofs2, 4, 1, massf );
			pos++;
			if ( pos > (unsigned long)num )
				break;
		}
	}

	//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
	sprintf( FileRec.name, "file%04lu", num+1 );
	FileRec.offset = ofs;
	FileRec.size = ofs2 - ofs;

	return 1;
}

