/*
 * A program that communicates with myTestDriver.
 */

#import <driverkit/IODeviceMaster.h>
#import <driverkit/IODevice.h>
#import <mach/mach.h>
#import <libc.h>
#import "HayesESP.h"

int	prescale[4] = {1, 2, 4, 8};

void 
arg_error()
{
    printf("usage: chbaud [n]\n");
    printf("args: n    Set baud rate multiplier\n");
    printf("             0 - baud rate x1\n");
    printf("             1 - baud rate x2\n");
    printf("             2 - baud rate x4\n");
    printf("             3 - baud rate x8\n");
    exit(-1);
}

void
main(int argc, char *argv[])
{
    IOReturn        ret;
    IOObjectNumber  tag;
    IOString        kind;
    IOIntParameter  value;
    unsigned int    count = IO_MAX_PARAMETER_ARRAY_LENGTH, unit = 0;
    char 	    name[80];
    IODeviceMaster *devMaster;

    /* Look up the test driver, using IODeviceMaster. */
    devMaster = [IODeviceMaster new];
    sprintf(name, "%s%d", my_DEVICE_NAME, unit);
    ret = [devMaster lookUpByDeviceName:name objectNumber:&tag 
	deviceKind:&kind];
    if (ret != IO_R_SUCCESS) { /* handle the error */
	fprintf(stderr, "Lookup failed: %s\n", 
		[IODevice stringFromReturn:ret]);
	exit(-1);
    }

    /* Get the value of the test driver's parameter. */
    ret = [devMaster getIntValues:value 
		forParameter:get_PARAMETER_NAME objectNumber:tag
		count:&count];
    if (ret != IO_R_SUCCESS) { /* handle the error */
        fprintf(stderr, "Failed to get parameter value: %s\n", 
		    [IODevice stringFromReturn:ret]);
        exit(-1);
    }

    if (argc > 2) {
        arg_error();
    }

    if (argc == 1) {
    	printf("Hayes ESP baud rate x%d\n", prescale[value[0]]);
        exit(0);
    }

    value[0] = atoi(argv[1]) % 4;
    /* Set the value of the test driver's parameter. */
    ret = [devMaster setIntValues:value 
		forParameter:set_PARAMETER_NAME objectNumber:tag
		count:count];
    if (ret != IO_R_SUCCESS) { /* handle the error */
        fprintf(stderr, "Failed to set parameter value: %s\n", 
		    [IODevice stringFromReturn:ret]);
        exit(-1);
    }
    printf("Hayes ESP baud rate x%d\n", prescale[value[0]]);
    exit(0);
}
