/*
 * rawdevice.c -- Machine/OS dependent raw device code.
 *
 *  Copyright 1997 (unix code)  John E. Stone (j.stone@acm.org)
 *
 *  $Id: rawdevice.c,v 1.4 1998/02/18 13:20:08 johns Exp $
 *
 */

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include "rawdevice.h" /* protos and types for this file */

typedef struct {
  int fd;        /* MIDI port device file descriptor */
} devstruct;

int dev_open(char * devname, DevHandle * devhandleptr, int *iofd) {
  devstruct * dev;
  *iofd = -1;
  *devhandleptr = NULL;

  dev = malloc(sizeof(devstruct));
  if (dev == NULL)
    return -1;

  dev->fd = open(devname, O_RDWR);

  if (dev->fd == -1) {
    free(dev);
    return -1;  /* failed open of dev port */
  }

  *devhandleptr = (DevHandle) dev;
  *iofd = dev->fd; 
  return 0;
}


int dev_write(DevHandle devhandle, char * buf, int sz) {
  devstruct * dev = (devstruct *) devhandle;

  return write(dev->fd, buf, sz);
}


int dev_read(DevHandle devhandle, char * buf, int sz) {
  devstruct * dev = (devstruct *) devhandle;

  return read(dev->fd, buf, sz);
}


int dev_close(DevHandle * devhandleptr) {
  devstruct * dev = (devstruct *) (*devhandleptr);

  if (dev == NULL)
    return -1;

  close(dev->fd);

  free(*devhandleptr);
  *devhandleptr = NULL;

  return 0;
}


