#include "ma_wtn.h"

char *CMassWtn::GetIdent( void )
{
	static char Ident[] = "WTN (Moorhuhn2)b";

	return Ident;
}

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

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

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

	if ( memcmp( buf, "MUDGE4.008/19/2000Copyright by Witan Entertainment B.V.", 56 ) == 0 )
		return 1;
	else
		return 0;
}

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

	if ( massf == NULL )
		return;

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

	fseek( massf, 60, SEEK_SET );
	fread( &lib_start, 4, 1, massf );
	fseek( massf, lib_start, SEEK_SET );
	do {
		fread( &wtnRec, 9, 1, massf );
		fseek( massf, wtnRec.name_len, SEEK_CUR );
		if ( wtnRec.rec_type == 1 )
			fread( &wtnRec.subfiles_count, 4, 1, massf );
		else {
			fread( &wtnRec.subfiles_count, 16, 1, massf );
			files_count ++;
		}
	} while ( (unsigned long)ftell( massf ) != filesize );
}

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

	//read
	do {
		if ( fread( &wtnRec, 9, 1, massf ) != 1 )
			return 0;
		if ( wtnRec.name_len >= wtnNameLen ) {
			//read as much as i can, and skip rest
			fread( &wtnRec.name, wtnNameLen, 1, massf );
			fseek( massf, wtnRec.name_len - wtnNameLen , SEEK_CUR );
			wtnRec.name_len = wtnNameLen-1;
		}
		else
			fread( &wtnRec.name, wtnRec.name_len, 1, massf );
		wtnRec.name[ wtnRec.name_len ] = '\0';

		if ( wtnRec.rec_type == 1 )
			fread( &wtnRec.subfiles_count, 4, 1, massf );
		else {
			fread( &wtnRec.subfiles_count, 16, 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( wtnRec.name );
	FileRec.offset = wtnRec.offset ^ 0xFFAA5533;
	FileRec.size   = wtnRec.size   ^ 0x3355AAFF;

	return 1;
}

unsigned long CMassWtn::Extract( unsigned long offset, unsigned long size, unsigned char *output )
{
	unsigned long	s;

	if ( massf == NULL )
		return 0;

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

	unsigned long	i;

	for( i=0; i<s; i++ )
		output[ i ] ^= 0x88;
		
	return s;
}
