#include <stdio.h>
#include <ftdi.h>
#include "fiber-switch.h"

struct ftdi_context ftdic;

int activate(int sw, int out)
{
	unsigned char c = 0;
	int config[3][2] = { {SW1_OUT1, SW1_OUT2},
			   {SW2_OUT1, SW2_OUT2},
			   {SW3_OUT1, SW3_OUT2} };

	if (sw<1 || sw > 3) {
		fprintf(stderr, "Switch index %d, outside allowed range\n", sw);
		return -1;
	}
	if (out < 1 || out > 2) {
		fprintf(stderr, "Output index %d, outside allowed range\n", out);
		return -1;
	}

	if(ftdi_usb_open(&ftdic, 0x0403, 0x6015) < 0) {
		printf("Can't open FTDI\n");
		return -1;
	}

	printf("Driving switch %d to output %d\n", sw, out);

	ftdi_enable_bitbang(&ftdic, config[sw-1][out-1]);
	c = config[sw-1][out-1];
	printf("c=%02X\n", c);
	ftdi_write_data(&ftdic, &c, 1);
	sleep(1);
	c = 0;
	ftdi_write_data(&ftdic, &c, 1);

	ftdi_usb_close(&ftdic);

	return 0;
}

int main(int argc, char *argv[])
{
	int sw, out;

	ftdi_init(&ftdic);

	if (argc<3) {
		fprintf(stderr, "%s: not enough arguments\n", argv[0]);
		return -1;
	}

	sw = atoi(argv[1]);
	out = atoi(argv[2]);

	return activate(sw, out);
}
