#import <stdio.h>
#import <CoreServices/CoreServices.h>
#import <Foundation/Foundation.h>
#import "Resource.h"
#import "ScenarioResources.h"
#import "Dumper.h"

Size get_destination_size(Ptr compressed)
{
    return *((unsigned long*)compressed);
}

void decompress(void *compressed, void *uncompressed)
{
    unsigned char *A3 = compressed,*A4 = uncompressed;
    unsigned long D2, D4, D0, D1;
    A3 += 4;
    D0 = D1 = D2 = 0;
    D4 = get_destination_size(compressed);

    while (D4 > D2)
    {
        D0 = (unsigned char)*A3++;

        if (D0 >= 0x80)
        {
            D0 -= 0x7F;
            D2 += D0;
            while (D0) {*A4++ = (unsigned char)*A3++; D0--;}
        }
        else
        {
            D0 += 3;
            D1 = (unsigned char)*A3++;
            D2 += D0;
            while (D0) {*A4++ = (unsigned char)D1; D0--;}
        }
    }
}

int main(void)
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    ScenarioResources *rsrc = [[ScenarioResources alloc] initWithContentsOfFile:@"/Volumes/Classic/Pathways/Shapes"];
    unsigned long theResId;
    
    for (theResId=128;theResId<204;theResId++) {
	Resource *theAnalyzedRsrc = [rsrc resourceOfType:@".256" index:theResId load:YES];
	NSData *_data = [theAnalyzedRsrc data];
	unsigned long cLen = [_data length], dLen;
	char *data = malloc(cLen), *uData;
	[_data getBytes:data];
	dLen = get_destination_size(data);

	if (dLen != 0)  {
	    printf("This resource (id %lu) is %lu bytes, and will be %lu bytes when decompressed.\n",theResId,cLen,dLen);
	    uData = malloc(dLen);
	    decompress(data,uData);
	    dump_shapes(uData, theResId, dLen);
	    free(uData);
	}
	free(data);
	[theAnalyzedRsrc release];
    }
    [pool release];
    return 0;
}
