#include <stdlib.h>
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "serial.h"
#define MAX_PATH 20


static struct termios old_term;

int
init_serial(int n)
{
    char path[MAX_PATH];
    int fd;
    struct termios term;
    
    snprintf(path, MAX_PATH - 1, "%s/%s%d", SERIAL_DIR, SERIAL_PREFIX, n);
    fd = open(path, O_RDWR | O_NOCTTY);
    
    if(fd >= 0) {
	tcgetattr(fd, &old_term);        
	memset(&term, 0, sizeof(struct termios));
	
	term.c_iflag |= (IGNBRK);
	term.c_oflag |= (0);
	term.c_cflag |= (CS8 | CLOCAL | CREAD | B1200); 
	term.c_lflag |= (0);
	
	tcsetattr(fd, TCSANOW, &term);
    } 
    else {
	printf("%s\n", path);
	perror("");
	fprintf(stderr, "Can not open serial port specified\n");
	return -1;
    }
    
    return fd;
}


int 
close_serial(int fd)
{
    tcsetattr(fd, TCSANOW, &old_term);
    close(fd);
    
    return 0;
}


