#include "ma_grp.h"

char *CMassGrp::GetIdent( void )
{
	static char Ident[] = "GRP (Duke3D)b";

	return Ident;
}

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

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

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

	if ( memcmp( buf, "KenSilverman", 12 ) == 0 )
		return 1;
	else
		return 0;
}

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

	if ( massf == NULL )
		return;

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

	fseek( massf, 12, SEEK_SET );
	fread( &files_count, 4, 1, massf );
	lib_start = 16;
	data_start = lib_start + 16 * files_count;
}

int	 CMassGrp::ReadRec( long num )
{
	unsigned long	i;

	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;
	}
	else {
		pos = lib_start + SizeOfGrpRec * num;
		if ( fseek( massf, pos, SEEK_SET ) != 0 )
			return 0;
	}

	//read
	if ( fread( &grpRec, SizeOfGrpRec, 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;
	
	//get info
//	sprintf( FileRec.name, "file%04lu", num+1 );
	memcpy( FileRec.name, grpRec.name, 12 );
	FileRec.name[ 12 ] = 0;
	FileRec.size = grpRec.size;
	//this calculates offset of file. 'coz grp have only size info stored
	if ( num == -1 )
		num = next_rec_num - 1;
	pos = 0;
	fseek( massf, lib_start, SEEK_SET );
	for( i=0; i<(unsigned long)num; i++ ) {
		fread( &grpRec, SizeOfGrpRec, 1, massf );
		pos += grpRec.size;
	}
	FileRec.offset = data_start + pos;

	return 1;
}

