#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include "gpios.h"

//#define NOIO

int main(int argc, char **argv){	
	int i,j;
	int gpio[128];
	int oldstate[128], state[128];
	int ngpios;
	struct timeval tv;
	fd_set read_fd;
	char *str = NULL;
	int lenStr = 0;

	ngpios = argc - 1;
	
	for(i=0;i<128;i++)
		gpio[i] = -1;

	for(i=0;i<ngpios;i++){
		j = atoi(argv[i+1]);
		gpio[i] = j;
		oldstate[i] = -1;
	}

	#ifndef NOIO
	gpioInit();
	#endif

	do{
		tv.tv_sec=0;
		tv.tv_usec=1000;
		FD_ZERO(&read_fd);
		FD_SET(0,&read_fd);
	
		if(select(1, &read_fd,NULL,NULL,&tv) == -1)
			return 0;
	
		if(FD_ISSET(0,&read_fd)){
			
			getline(&str, &lenStr, stdin);
			i=strlen(str);
			if(str[i-1] =='\n')
				str[i-1] = 0x00;

			if(str == NULL)	
				break;

			if(str[0] == 'q')
				break;

			else if(str[0] == 'o'){
				printf("GPIO #:");
				getline(&str, &lenStr, stdin);
				i=atoi(str);

				#ifndef NOIO
				if(i >=0 && i < 128)
					gpioSetDir(i, 1);
				#endif
				printf("%i --> output\n",i);
			}else if(str[0] == 'i'){
				printf("GPIO #:");
				getline(&str, &lenStr, stdin);
				i=atoi(str);
				
				#ifndef NOIO
				if(i >=0 && i < 128)
					gpioSetDir(i, 0);
				#endif
				printf("%i --> input\n",i);
			}else if( str[0] >= '0' && str[0] <='9'){ //toggle
				i = atoi(str);
				if(i >=0 && i < 128){
					#ifndef NOIO
					j = gpioGet(i);
					printf("%i: %i --> %i\n",i,j,!j);
					gpioSet(i, !j);
					#endif
				}
			}
		}

		
		for(i=0;i<ngpios;i++){
			#ifdef NOIO
			state[i] = 0;
			#else
			state[i] = gpioGet( gpio[i] );
			#endif

			if( state[i] != oldstate[i] )
				printf("%i: %i --> %i\n",gpio[i],oldstate[i],state[i]);
			oldstate[i] = state[i];
		}


	}while(1);
	
	#ifndef NOIO
	gpioCleanup();
	#endif

	if(str != NULL)
		free(str);

	return 0;
}


