#include "ma_swine.h"

char *CMassSwine::GetIdent( void )
{
	static char Ident[] = "SWN (Swine)b";

	return Ident;
}

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

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

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

	if (( memcmp( buf, "Sr\x1A\x1B", 4 ) == 0 ) &&
		( memcmp( &buf[8], "PACK", 4 ) == 0 ))
		return 1;
	else
		return 0;
}

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

	if ( massf == NULL )
		return;

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

	lib_start = 16;
	fseek( massf, 12, SEEK_SET );
	fread( &lib_size, 4, 1, massf );
	data_start = 16 + lib_size;
	files_count = 0;
	while ( (unsigned long)ftell( massf ) < lib_size + 16 ) {
		fread( &swineRec, 2, 1, massf );
		fseek( massf, swineRec.name_len + 13, SEEK_CUR );
		files_count++;
	} ;
}

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

	//seek and read
	do {
		if ( fread( &swineRec, 2, 1, massf ) != 1 )
			return 0;
		if ( swineRec.name_len >= swineNameLen ) {
			fread( &swineRec.name, swineNameLen, 1, massf );
			swineRec.name[ swineNameLen-1 ] = 0;
			fseek( massf, swineRec.name_len - swineNameLen +1, SEEK_CUR );
		}
		else {
			fread( &swineRec.name, swineRec.name_len, 1, massf );
			swineRec.name[ swineRec.name_len ] = 0;
		}
		fread( &swineRec.offset, 13, 1, massf );
		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( swineRec.name );
	FileRec.offset 	= swineRec.offset + data_start;
	FileRec.size    = swineRec.size;

	return 1;
}

