#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
#include <string.h>


int main(int argc, char *argv[])
{
int fd;
int speed;
struct termios raw;
char buf[256];
char big[1024];
int bigcount = 0;
int count, idx;

	// Open the port
	if ((fd = open ("/dev/ser1", O_RDWR)) == -1)
	{
	       fprintf(stderr, "Error with open() on /dev/ser1. Make sure exists.\n");
	       perror (NULL);
	       exit(EXIT_FAILURE);
	}

	// Get the attributes
	if (tcgetattr( fd, &raw))
	{
	       close( fd );
	       return -1;
    }

    // Set input baud rate
	speed = 115200;
    cfsetispeed(&raw, speed);
	cfsetospeed(&raw, speed);

	raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON );

	raw.c_oflag &= ~(OPOST);

    raw.c_cflag &= ~(CSIZE|IHFLOW|OHFLOW);
    raw.c_cflag |= CS8 | CREAD | CLOCAL;
	raw.c_cflag &= ~CSTOPB;
	raw.c_cflag &= ~PARENB;

	raw.c_lflag &= ~(ECHO | ICANON | ISIG | ECHOE | ECHOK | ECHONL | IEXTEN);

	raw.c_cc[VMIN] =  1;
	raw.c_cc[VTIME] = 0;

	if ( tcsetattr( fd, TCSADRAIN, &raw ) == -1 )   // CHECK FOR -1 failure here - this is the actual "set" and it must succeed on nothing may have changed
	{
	       fprintf(stderr, "Error with tcsetattr() on /dev/ser1.\n");
	       perror (NULL);
	       exit(EXIT_FAILURE);
	}

	sprintf( buf, "waiting for data..." );
	write( fd, buf, strlen(buf) );
	buf[0] = 0;
    while ( (buf[0] != 0x03) && (bigcount != sizeof(big) - 1) )  // end loop on ^C
    {
    	count = read( fd, buf, sizeof(buf)-1 );
    	idx = 0;
    	while ( (count > 0) && (bigcount != sizeof(big) - 1) )
    	{
    		big[bigcount++] = buf[idx++];
    		count--;
    	}
    }
    big[bigcount] = 0;
    printf( "%s\n", big );

    close( fd );
	return EXIT_SUCCESS;
}
