#include "ma_roll.h"

char *CMassRoll::GetIdent( void )
{
	static char Ident[] = "IDX (RollCage)b";

	return Ident;
}

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

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

	int		i;

//	i = strlen( MassFileName );
//	if ( i < 4 )
//		return 0;

//	i -= 4;
	if ( strcmp( MassFileExt, "idx" ) == 0 ) {
		sprintf( ImgFileName, "%s%s", MassFilePath, MassFileName );
		//skontrolujem ci existuje aj name.dat
		//ImgFileName[ i ] = 0; 
		strcat( ImgFileName, ".img" );
		ImgFile = fopen( ImgFileName, "rb" );
		if ( ImgFile != NULL ) {
			fclose( ImgFile );
			fseek( massf, 0, SEEK_END );
			if ( ftell( massf ) % 16 == 0 )
				return 1;
		}
	}

	return 0;
}

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

	if ( massf == NULL )
		return;

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

	files_count = filesize / 16;
	lib_start = 0;
}

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

	//read
	if ( fread( &rollRec, SizeOfRollRec, 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
	num = next_rec_num - 1;
	sprintf( FileRec.name, "file%04lu", num+1 );
	FileRec.offset	= rollRec.offset;
	FileRec.size	= rollRec.size;

	return 1;
}

//data are in other file
unsigned long CMassRoll::Extract( unsigned long offset, unsigned long size, unsigned char *output )
{
	unsigned long	s;

	if ( massf == NULL )
		return 0;

	if ( offset + size > FileRec.size )
		return 0;

    ImgFile = fopen( ImgFileName, "rb" );

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

	fclose( ImgFile );

	return s;
}
