#include "ma_ecou.h"

#include "stdlib.h"

char *CMassEcou::GetIdent( void )
{
	static char Ident[] = "001 (unknown economy)b";

	return Ident;
}

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

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

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

	if (( buf[0] == 0 ) && ( buf[17] == 32 ))
		return 1;
	else
		return 0;
}

void CMassEcou::GetFileMainInfo( void )
{
	char			count[ 9 ];
	unsigned long	i;

	files_count = 0;

	if ( massf == NULL )
		return;

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

	fseek( massf, 17, SEEK_SET );
	fread( &count, 8, 1, massf );
	count[ 8 ] = 0;
	files_count = atol( count );
	lib_start = 25;

	// precitam vsetky recordy, aby som nasiel zaciatok dat
	for( i=0; i<files_count; i++ ) {
		fread( &EcouRec.name_len, 1, 1, massf );
		fread( &EcouRec.name, EcouRec.name_len, 1, massf );
		fread( &EcouRec.size_c_len, 1, 1, massf );
		fread( &EcouRec.size_c, EcouRec.size_c_len, 1, massf );
	}

	data_start = ftell( massf );
	next_file_offset = 0;
}

int	 CMassEcou::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 ) );

	if (( next_set ) && ( (signed)next_rec_num == num ))
		num = -1;

	//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 {
		fseek( massf, lib_start, SEEK_SET );
		pos = 0;
		next_file_offset = 0;
	}

	//seek and read
	do {
		fread( &EcouRec.name_len, 1, 1, massf );
		fread( &EcouRec.name, EcouRec.name_len, 1, massf );
		EcouRec.name[ EcouRec.name_len ] = 0;
		fread( &EcouRec.size_c_len, 1, 1, massf );
		fread( &EcouRec.size_c, EcouRec.size_c_len, 1, massf );
		EcouRec.size_c[ EcouRec.size_c_len ] = 0;
		EcouRec.size = atol( EcouRec.size_c );
		next_file_offset += EcouRec.size;
		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
	pos = 0;
	while (( EcouRec.name[ pos ] == '\\' ) || ( EcouRec.name[ pos ] == '/' ))
		pos ++;

	FileRec.SetName( &EcouRec.name[ pos ] );
	FileRec.offset = data_start + next_file_offset - EcouRec.size;
	FileRec.size = EcouRec.size;
	FileRec.set = 1;

	return 1;
}
