#include "ma_dune2.h"

char *CMassDune2::GetIdent( void )
{
	static char Ident[] = "PAK (Dune 2)b";

	return Ident;
}

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

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

	unsigned long	ul;

	if ( strcmp( MassFileExt, "pak" ) == 0 ) {
		fseek( massf, 0, SEEK_SET );
		fread( &ul, 4, 1, massf );
		if ( fseek( massf, ul - 4, SEEK_SET ) != 0 )
			return 0;
		if ( fread( &ul, 4, 1, massf ) != 1 )
			return 0;
		if ( ul == 0 )
			return 1;
	}

	return 0;
}

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

	if ( massf == NULL )
		return;

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

	unsigned long	ul;
	unsigned char	uc;

	lib_start = 0;
	fseek( massf, 0, SEEK_SET );
	do {
		fread( &ul, 4, 1, massf );
		if ( ul != 0 ) {
			files_count++;
			do {
				fread( &uc, 1, 1, massf );
			} while( uc != 0 );
		}
	} while ( ul != 0 );

}

int	 CMassDune2::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;
		pos = next_rec_num - 1;
		num = next_rec_num;
	}
	else {
		pos = 0;
	}

	unsigned long	ofs, i;
	unsigned char	c;


	//seek and read
	do {
		if ( fread( &ofs, 4, 1, massf ) != 1)
			return 0;
		if ( pos > (unsigned long)num )
			break;

		dune2Rec.offset = ofs;
		i = 0;
		do {
			fread( &c, 1, 1, massf );
			if ( i < dune2NameLen )
				dune2Rec.name[ i++ ] = (char)c;
			if ( i + 1 == dune2NameLen )
				dune2Rec.name[ dune2NameLen-1 ] = 0;
		} while( c != 0 );
		pos++;
	} while ( 1 );

	//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( dune2Rec.name );
	FileRec.offset	= dune2Rec.offset;
	if ( ofs == 0 )
		ofs = filesize;
	FileRec.size	= ofs - dune2Rec.offset;

	return 1;
}
