#include "serial.h"
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>

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

/*********************************************************************
*              Set up a new serial port. 
*********************************************************************/
serial_t * serial_Init (char * device, int baud) {
  serial_t * self;
  struct termios newtio;

  self = malloc(sizeof(serial_t));
  assert(self != NULL);
      
  self->Device            = strdup(device);
  self->Baud              = baud;
  self->Handle            = open(device, O_RDWR | O_NOCTTY ); 

  assert(self->Handle > 0); 
  bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */
  newtio.c_cflag = B4800 | CS8 | CLOCAL | CREAD;
  newtio.c_iflag = IGNPAR;
  newtio.c_oflag = 0;
  newtio.c_lflag = ICANON;
  tcflush(self->Handle, TCIFLUSH);
  tcsetattr(self->Handle,TCSANOW,&newtio);
  
  return self;
}

/**************************************************************
*                 Free Resources
**************************************************************/
void serial_Destroy (serial_t * self) {

  close(self->Handle);

  if (self != NULL) {
    free(self);
  }
}

/************************************************************
*               Write to the Data port
************************************************************/
void serial_WriteData (serial_t * self, char * data) {

  write(self->Handle, data, strlen(data));

}

/**********************************************
*          unified port read
**********************************************/
void serial_Read(serial_t * self, char * data) {


} 




