#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>

int
openSerialPort(char* dev, int baud_rate)
{

    int fd = open(dev, O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd < 0)
        return -1;

    // Set blocking mode, program will wait for input
    fcntl(fd, F_SETFL, 0);
    // fcntl(fd, F_SETFL, FNDELAY);  // Non blocking mode

    struct termios options;
    tcgetattr(fd, &options);
    cfsetispeed(&options, baud_rate);
    cfsetospeed(&options, baud_rate);

    options.c_cflag |= (CLOCAL | CREAD);

    options.c_cflag &= ~(PARENB | CSTOPB); // No parity, one stop bit
    options.c_cflag &= ~CSIZE; // Clear the character size bits
    options.c_cflag |= CS8;    // 8 bits

    options.c_cflag &= ~CRTSCTS; // No hardware flow control

    // Raw mode, just the facts
    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);

    // Software flow control
    options.c_iflag &= ~(IXON | IXOFF | IXANY);

    // Raw output mode
    options.c_oflag &= ~OPOST;

    tcsetattr(fd, TCSAFLUSH, &options);

    return fd;
}

int
main(int argc, char** argv)
{

    if (argc != 2)
    {
        fprintf(stderr, "usage: %s devicename (e.g. /dev/ttyS1)\n", argv[0]);
        return -1;
    }

    int fd = openSerialPort(argv[1], B9600);

    if (fd < 0)
    {
        fprintf(stderr, "Error opening device '%s'\n", argv[1]);
        return -1;
    }

    fprintf(stderr,
            "Opened device '%s' on file descriptor %d\n",
            argv[1], fd);


    while (true)
    {
        char buffer[256];
        int nbytes;
        nbytes = read(fd, buffer, sizeof(buffer) - 1);
        buffer[nbytes] = 0;
        printf(buffer);
    }

    close(fd);
}

