//
//  EXPSwitchElement.m
//  XMLTest
//
//  Created by Ashley on 26/05/2007.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "EXPSwitchElement.h"
#import "EXPExpressionList.h"

@implementation EXPSwitchElement

- (id) init
{
	self = [super init];
	_statements = [[NSMutableArray alloc] init];
	return self;
}

- (void) setStatements:(id) statements
{
	[statements retain];
	[_statements release];
	_statements = statements;
}

- (id) statements
{
	return _statements;
}

- (void) addStatement:(id) statement
{
	[[self statements] addObject:statement];
}

- (void) generateParseTree
{
	[super generateParseTree];
	
	NSArray *statements = [self statements];
	int i;
	for (i=0; i<[statements count]; i++) {
		NSMutableDictionary *dict = [statements objectAtIndex:i];
		EXPExpressionList *list = [dict objectForKey:@"list"];
//		[list generateParseTree];
		EXPExpression *exp = [EXPExpression expression:list];
		[dict setObject:exp forKey:@"exp"];
		[exp release];

	}
}

- (BOOL) compile:(EXPStackMachine *)machine switchAddress:(NSMutableArray *)switchAddresses andMapAddresses:(NSMutableArray *)mapAddresses 
		 error:(NSError **)error
{
	int switchAddress = [machine pc];
	NSNumber *switchAddressNumber = [[NSNumber alloc] initWithInt:switchAddress];
	[switchAddresses addObject:switchAddressNumber];
	[switchAddressNumber release];
	
	BOOL success;
	success = [super compile:machine error:error withArguments:nil];
	[machine putUInt:HLT];

	int mapAddress = [machine pc];
	NSNumber *mapAddressNumber = [[NSNumber alloc] initWithInt:mapAddress];
	[mapAddresses addObject:mapAddressNumber];
	[mapAddressNumber release];

	
	NSArray *statements = [self statements];
	int i;
	for (i=0; i<[statements count]; i++) {
		NSMutableDictionary *dict = [statements objectAtIndex:i];
		EXPExpression *exp = [dict objectForKey:@"exp"];
		success = [exp compile:machine error:error];
		
		EXPElement *element = [dict objectForKey:@"element"];
		unsigned int address = [element address];
		[machine putUInt:STRV];
		[machine putUInt:address];
		
	}
	
	[machine putUInt:HLT];

	return YES;
}

- (void) clear
{
	[self setStatements:nil];
	[super clear];
}

- (void) dealloc
{
	[_statements release];
	[super dealloc];
}

@end
