#import "PhidgetServoController.h"
	
CPhidgetServoHandle servo;

@implementation PhidgetServoController

int gotAttach(CPhidgetHandle phid, void *context) {
	[(id)context phidgetAdded];
	return 0;
}

int gotDetach(CPhidgetHandle phid, void *context) {
	[(id)context phidgetRemoved];
	return 0;
}

- (void)phidgetAdded
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	int serial, version;
	int numMotors;

	CPhidget_getSerialNumber((CPhidgetHandle)servo, &serial);
	CPhidget_getDeviceVersion((CPhidgetHandle)servo, &version);
	CPhidgetServo_getMotorCount(servo,&numMotors);
	
	CPhidgetServo_setEngaged(servo, 0, 1);
	
	[connectedField setTitleWithMnemonic:@"PhidgetServo Connected"];
	[serialField setTitleWithMnemonic:[NSString stringWithFormat:@"%d", serial]];
	[versionField setTitleWithMnemonic:[NSString stringWithFormat:@"%d", version]];
	[numberOfServosField setTitleWithMnemonic:[NSString stringWithFormat:@"%i", numMotors]];

	[pool release];
}

- (void)phidgetRemoved
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	[connectedField setTitleWithMnemonic:@"PhidgetServo Removed"];
	[serialField setTitleWithMnemonic:@""];
	[versionField setTitleWithMnemonic:@""];
	[numberOfServosField setTitleWithMnemonic:@""];

	[pool release];
}

- (IBAction)moveServo:(id)sender
{
	CPhidgetServo_setPosition(servo, [sender selectedTag], [[sender cellWithTag:[sender selectedTag]] intValue]);
	printf("Position: %d\n",[[sender cellWithTag:[sender selectedTag]] intValue]);
}

/*
* This gets run when the GUI gets displayed
*/
- (void)awakeFromNib
{
	int serial = -1, remote = 0;
	NSArray *args = [[NSProcessInfo processInfo] arguments];
	if([args count] > 1)
	{
		if([[args objectAtIndex:1] isEqualToString:@"remote"])
			remote = 1;
		serial = strtol([[args objectAtIndex:[args count]-1] UTF8String], NULL, 10);
		if(serial == 0) serial = -1;
	}
	
	[mainWindow setDelegate:self];
	
	CPhidgetServo_create(&servo);
	
	CPhidget_set_OnAttach_Handler((CPhidgetHandle)servo, gotAttach, self);
	CPhidget_set_OnDetach_Handler((CPhidgetHandle)servo, gotDetach, self);
	
	if(remote)
		CPhidget_openRemote((CPhidgetHandle)servo, serial, NULL, NULL);
	else
		CPhidget_open((CPhidgetHandle)servo, serial);
}

- (void)windowWillClose:(NSNotification *)aNotification {
	CPhidget_close((CPhidgetHandle)servo);
	CPhidget_delete((CPhidgetHandle)servo);
	servo = NULL;
	[NSApp terminate:self];
}

@end
