#include "ma_crism.h"

char *CMassCrismon::GetIdent( void )
{
	static char Ident[] = "PAQ(Crismon land,10Tons)";

	return Ident;
}

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

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

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

	if ( memcmp( buf, "paq\0", 4 ) == 0 )
		return 1;
	else
		return 0;
}

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

	if ( massf == NULL )
		return;

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

	unsigned char	uc;
	unsigned long	size;

	fseek( massf, 4, SEEK_SET );
	while ( ! feof( massf ) ) {
		//skip name
		do {
			fread( &uc, 1, 1, massf );
		} while ( uc != 0 );
		
		if ( fread( &size, 4, 1, massf ) != 1 )
			break;
		if ( fseek( massf, size, SEEK_CUR ) != 0 )
			break;

		files_count++;
	} ;
	
	lib_start = 4;
}

int	 CMassCrismon::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;
		num = next_rec_num;
	}
	else {
		pos = 0;
		
		fseek( massf, lib_start, SEEK_SET );
	}

	//(find and ) read record
	unsigned char		uc;
	unsigned long		i;

	do {
		i = 0;
		do {
			fread( &uc, 1, 1, massf );
			if ( i < FileNameWithPathMaxLen )
				crismonRec.name[ i++ ] = uc;
		} while ( uc != 0 );

		if ( fread( &crismonRec.size, 4, 1, massf ) != 1 )
			return 0;

		crismonRec.offset = ftell( massf );
		
		//skip data
		if ( fseek( massf, crismonRec.size, SEEK_CUR ) != 0 )
			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( crismonRec.name );
	FileRec.offset = crismonRec.offset;
	FileRec.size = crismonRec.size;
	FileRec.set = 1;

	return 1;
}

