#include "ma_umod.h"

char *CMassUmod::GetIdent( void )
{
	static char Ident[] = "UMOD (Unreal Tournament)";

	return Ident;
}

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

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

	unsigned long	ul, ul2;

	if (( strcmp( MassFileExt, "umod" ) == 0 ) ||
		( strcmp( MassFileExt, "umo" ) == 0 )) { //dos
		fseek( massf, 0, SEEK_END );
		ul = ftell( massf );
		fseek( massf, ul-12, SEEK_SET );
		fread( &ul2, 4, 1, massf );
		if ( ul2 == ul )
			return 1;
	}
	return 0;
}

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

	if ( massf == NULL )
		return;

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

	unsigned char	uc;

	fseek( massf, filesize - 16, SEEK_SET );
	fread( &lib_start, 4, 1, massf );
	fseek( massf, lib_start, SEEK_SET );
	fread( &uc, 1, 1, massf );
	lib_start += 1;
	files_count = uc;
}

int	 CMassUmod::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;
		if ( fseek( massf, lib_start, SEEK_SET ) != 0 )
			return 0;
	}

	//read
	do {
		fread( &umodRec.namelen, 1, 1, massf );
		if ( fread( &umodRec.name, umodRec.namelen, 1, massf ) != 1 )
			return 0;
		if ( fread( &umodRec.offset, 12, 1, massf ) != 1 )
			return 0;
		pos++;
	} while ( pos <= (unsigned long)num );

	//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( umodRec.name );
	FileRec.offset 	= umodRec.offset;
	FileRec.size	= umodRec.size;

	return 1;
}
