#include <unistd.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>  /* String function definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <sys/ioctl.h>
#include "serialio.h"

int fd;

serialio_data_t* serialio_new(){
	serialio_data_t* serialio;

        serialio = (serialio_data_t*) malloc (sizeof(serialio_data_t));

        serialio->fd = 0;

        return serialio;
}

int serialio_open(serialio_data_t* serialio){
	int status;
	serialio->fd = open ("/dev/ttyS1", O_RDWR | O_NOCTTY | O_NDELAY);
	if (serialio->fd > 0){
		ioctl(serialio->fd, TIOCMGET, &status);
//                status &= ~TIOCM_RTS;
                status |= TIOCM_DTR;
                ioctl(fd, TIOCMSET, &status);
	}
	return serialio->fd;
}

void serialio_close(serialio_data_t* serialio){
	if (serialio->fd) close (serialio->fd);
}

int serialio_get_foot (serialio_data_t* serialio){
	int status;
	if (serialio->fd){
		ioctl(serialio->fd, TIOCMGET, &status);
		return (status & TIOCM_CTS); /* CTS = 32 */
	}else return -1;
}

int serialio_set_footled (serialio_data_t* serialio, int led){
	int status;
        if (serialio->fd){
                ioctl(serialio->fd, TIOCMGET, &status);
		if (led > 0) status &= ~TIOCM_RTS; else status |= TIOCM_RTS;
		ioctl(serialio->fd, TIOCMSET, &status);
                return TIOCM_RTS;
        }else return -1;
}

int serialio_toggle_footled (serialio_data_t* serialio){
	int status;
	if (serialio->fd){
                ioctl(serialio->fd, TIOCMGET, &status);
                status ^= TIOCM_RTS;
                ioctl(serialio->fd, TIOCMSET, &status);
                return (status & TIOCM_RTS);
        }else return -1;
}

/*
int main(int argc, char **argv){
	if (argc < 2){printf ("device als argument!\n");exit (0);}
	fd = open(argv[1], O_RDWR | O_NOCTTY | O_NDELAY);
	if (fd < 1){printf ("couldn't open\n");exit(0);}

	while(1){
		ioctl(fd, TIOCMGET, &status);
		printf ("DSR:%d ",(status & TIOCM_LE));
		printf ("DTR:%d ",(status & TIOCM_DTR));
		printf ("RTS:%d ",(status & TIOCM_RTS));
		printf ("TxD:%d ",(status & TIOCM_ST));
		printf ("RxD:%d ",(status & TIOCM_SR));
		printf ("CTS:%d ",(status & TIOCM_CTS));
		printf ("DCD:%d ",(status & TIOCM_CAR));
		printf ("CD: %d ",(status & TIOCM_CD));
		printf ("RNG:%d ",(status & TIOCM_RNG));
		printf ("DSR:%d ",(status & TIOCM_DSR));
		printf ("\n");
		sleep(1);
	}
}
*/
