#include "ma_gunme.h"

char *CMassGunMetal::GetIdent( void )
{
	static char Ident[] = "PCK(Gun Metal,Yeti Studios)";

	return Ident;
}

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

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

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


	unsigned long	ul;

	if ( strcmp( MassFileExt, "pck" ) == 0 ) {
		fseek( massf, 0, SEEK_SET );
		fread( &ul, 4, 1, massf );
		
		if ( ul < 4096 )
			return 1;
	}

	return 0;
}

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

	if ( massf == NULL )
		return;

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

	unsigned long	size, i;

	fread( &size, 4, 1, massf );
	files_count = size;

	lib_start = 4;

	if ( strcmp( MassFileName, "comsenglish" ) == 0 )
		xored_data = 0;
	else
		xored_data = 1;
}

int	 CMassGunMetal::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;
	
	//seek
	if ( num == -1 ) {
		if ( fseek( massf, next_rec_pos, SEEK_SET ) != 0 )
			return 0;

		pos = next_rec_num;
		num = next_rec_num;
	}
	else {
		pos = lib_start + sizeof( gunmetalRec ) * num;
		if ( fseek( massf, pos, SEEK_SET ) != 0 )
			return 0;
	}

	if ( fread( &gunmetalRec, sizeof( gunmetalRec ), 1, massf ) != 1 )
		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;

	unsigned char	buf[ 4 ];

	fseek( massf, gunmetalRec.offset, SEEK_SET );
	fread( buf, 4, 1, massf );

	//get info
	sprintf( FileRec.name, "File %i", (int) num );

	if ( memcmp( buf, "RIFF", 4 ) == 0 )
		strcat( FileRec.name, ".wav" );
	if (( buf[ 0 ] == 0xB8 ) && ( buf[ 1 ] == 0xA8 ))
		strcat( FileRec.name, ".dxt" );
	if (( buf[ 0 ] == 0xF8 ) && ( buf[ 1 ] == 0xC8 ) && ( buf[ 2 ] == 0xD9 ) && ( buf[ 3 ] == 0xCE ))
		strcat( FileRec.name, ".scr" );
	if (( buf[ 0 ] == 0xC1 ) && ( buf[ 1 ] == 0xAB ) && ( buf[ 2 ] == 0xAB ) && ( buf[ 3 ] == 0xAB ))
		strcat( FileRec.name, ".tri" );

	FileRec.offset = gunmetalRec.offset;
	FileRec.size = gunmetalRec.size;
	FileRec.set = 1;

	return 1;
}

unsigned long CMassGunMetal::Extract( unsigned long offset, unsigned long size, unsigned char *output )
{
	unsigned long	s;

	if ( massf == NULL )
		return 0;

	//no compression
	if ( fseek( massf, FileRec.offset + offset, SEEK_SET ) != 0 )
		return 0;
	s = fread( output, 1, size, massf );
	if ( s == 0 )
		return 0;

	unsigned long	i;

	if ( xored_data ) {

		for( i=0; i<s; i++ )
			output[ i ] ^= 0xAB;
	}
		
	return s;
}
