#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/signal.h>
#include <termio.h>

int main(int argc, char *argv[])
{
  fd_set rfds, wfds, efds;
  int fd, cntlc=0;
  char buf[10240];
  struct termio save, mode;
  if (argc<2)
    {
      fprintf(stderr, "usage: %s <device>\n", argv[0]);
      exit(1);
    }
  else
    if ((fd = open(argv[1], O_RDWR))<0)
      {
	fprintf(stderr, "%s: Can't open %s\n", argv[0], argv[1]);
	exit(1);
      }
  
  printf("Interactive mode.  (Cntl-C Cntl-C to quit).\n");
      
  ioctl(0, TCGETA, &save);
  ioctl(0, TCGETA, &mode);

  mode.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
  mode.c_oflag &= ~OPOST;
  mode.c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
  mode.c_cflag &= ~(CSIZE|PARENB);
  mode.c_cflag |= CS8;
  mode.c_cc[VMIN] = 0;
  mode.c_cc[VTIME] = 0;

  ioctl(0, TCSETA, &mode);

  while (cntlc<2)
    {
      int sel;
      struct timeval timeout;

      FD_ZERO(&rfds);
      FD_ZERO(&wfds);
      FD_ZERO(&efds);
      FD_SET(0, &rfds);
      
      if (cntlc==0)
	FD_SET(fd, &rfds);

      timeout.tv_usec = 0;
      timeout.tv_sec  = 1;

      sel = select(fd+1, &rfds, &wfds, &efds, (cntlc) ? &timeout : NULL);

      if (sel == 0)
	{
	  buf[0] = 3;
	  write(fd, buf, 1);
	  cntlc = 0;
	}
      else
	if (sel>0)
	  {
	    if (FD_ISSET(0, &rfds))
	      {
		int i, cc = read(0, buf, 1000);
		for(i = 0; i < cc; i++)
		  if (buf[i]==3)
		    cntlc++;
		  else
		    {
		      cntlc=0;
		      write(fd, buf+i, 1);
		    }
	      }
	    if (FD_ISSET(fd, &rfds))
	      {
		int i, cc = read(fd, buf, 1000);
		for(i = 0; i < cc; i++)
		  {
		    if (buf[i] == 10)
		      putchar(13);
		    putchar(buf[i]);
		  }
		fflush(stdout);
	      }
	  }
	else
	  {
	    shutdown(fd, 2);
	    fprintf(stderr, "select error\n");
	    exit(1);
	  }
    }
  ioctl(0, TCSETA, &save);
  return 0;
}


