
#import <appkit/appkit.h>

#import "XQ_InterchangeCell.h"
#import "XQ_UserFunction.h"
#import "XQ_InterfaceObject.h"

#import "Questor_API_Demo5.h"

@implementation Questor_API_Demo5

- callFunction:sender;
{
	const char *fnName = [functionName stringValue];
	int ac = [argCount intValue];
	id argList = nil;
	id returnValue = nil;
	int error = 0;
	int delivered = 0;
	int i;
	char *alert;
	
	if(theInterface == nil) {
		theInterface = [[XQ_Interface alloc] initForNewSheet];
		if(theInterface == nil) {
			NXRunAlertPanel("Communication Problem",
		    "Could not create a new sheet",
		    "OK", NULL, NULL);
		 return self;
		}
	}

	argList = [List new];
	for(i=0; i<ac; i++) {
		id cell = [[XQ_InterchangeCell alloc] init];
		[cell setDoubleValue:[[argMatrix cellAt: i:0]doubleValue]];
		[argList addObject: cell];
	}
	
	delivered = [theInterface XQ_callFunction: fnName
					arguments: argList
					returnValue: &returnValue
					error: &error];
	
	if(delivered != 0) {
		NXRunAlertPanel("Communication Problem",
		    "Could not communicate with Questor. Error code was %d",
		    "OK", NULL, NULL,
		    delivered);
	}
	
	if(error || delivered != 0) {
		[resultField setStringValue: "error"];
	} else  {
		[resultField setDoubleValue: [returnValue doubleValue]];
	}
	
	if(error) {
		
		switch(error) {
		case XQ_UNDEFINED_FUNCTION : 
			alert = "Undefined function!";
			break;
		case XQ_TOO_FEW_ARGUMENTS_FUNCTION : 
			alert = "Too few arguments!";
			break;
		case XQ_TOO_MANY_ARGUMENTS_FUNCTION : 
			alert = "Too many arguments!";
			break;
		case XQ_EXECUTION_ERROR : 
			alert = "Errors during execution!";
			break;
		default : 
			alert = "Unknown error!";
			break;
		}
		NXRunAlertPanel("Execution Problem", alert,
		    		"OK", NULL, NULL);
	}
	
	[returnValue free];
	[[argList freeObjects] free];
	
	return self;
}



@end
