//
//  EXPTernOp.m
//  ExpTest
//
//  Created by Ashley on 08/01/2007.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "EXPExpression.h"
#import "EXPUnaryOp.h"
#import "EXPBinOp.h"
#import "EXPTernOp.h"
//#import "EXPAssemblerConstants.h"
#import "EXPVirtualMachine.h"

@implementation EXPTernOp

- (id) initOp:(id)name withLeft:(id)left andRight:(id)right andThird:(id)third
{
	[super initOp:name withLeft:left AndRight:right];
	[self setThird:third];
	[self storeIndices];
	return self;
}

- (void) setThird:(id)third
{
	[third retain];
	[_third release];
	[self storeIndices];
	_third = third;
}

- (id) third
{
	return _third;
}

- (void) storeIndices
{
	[super storeIndices];
	EXPExpression *third = [self third];
	NSMutableArray *indices = [third indices];
	NSArray *superIndices = [self indices];
	int i;
	for(i=0; i<[superIndices count]; i++) {
		id index = [superIndices objectAtIndex:i];
		if (![indices containsObject:index]) {
			[indices addObject:index];
		}
	}
	
	[self setIndices:indices];
}

- (NSString *)elementType
{
	return @"ternaryop";
}

- (BOOL) isTypeCompatible
{
	EXPExpression *third = [self third];
	EXPExpressionType thirdType = [third expressionType];
	BOOL compatible;
	
	if (thirdType!=integerType) {
		compatible = NO;
		
	} else {
		compatible = [super isTypeCompatible];
	
	}
	
	return compatible;
}

/* - (BOOL) compile:(EXPVirtualMachine *)machine error:(EXPError *)err
{
	EXPExpression *left = [self left];
	EXPExpression *right = [self right];
	EXPExpression *third = [self third];
	
	[third compile:machine error:err];
	[machine putOpcode:BEQ mode:LONG];
	unsigned int branch1 = [machine ptr];
	[machine putUInt:0];
	
	[left compile:machine error:err];
	[machine putOpcode:BRA mode:LONG];
	unsigned int branch2 = [machine ptr];
	[machine putUInt:0];
	
	[machine putUInt:[machine ptr] at:branch1];
	[right compile:machine error:err];
	
	[machine putUInt:[machine ptr] at:branch2];
	
	return YES;
} */

- (NSString *)description
{
	return [NSString stringWithFormat:@"(%@) ? (%@) : (%@)", [[self third] description], [[self left] description], [[self right] description]];
}

- (double) result
{
	double y = [[self left] result];
	if ((int)y!=0) {
		return [[self right] result];
	} else {
		return [[self third] result];
	}
}

- (void)dealloc
{
//	printf("EXPTernOp - (void)dealloc\n");
	[_third release];
	[super dealloc];
}

@end