/*
 *  Copyright (C) 2009  Robert Millan
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#define _GNU_SOURCE 1

#include <termios.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <error.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int
main (int argc, char *argv[])
{
  struct termios term;
  int i;
  int fd;
  char c;
  char *command;
  char *expected_reply;

  if (argc != 3)
    {
      printf ("Usage: %s MODEM_DEVICE COMMAND\n", argv[0]);
      exit (1);
    }

  fd = open (argv[1], O_RDWR | O_NOCTTY);
  if (fd < 0)
    error (1, errno, "open");

  memset (&term, 0, sizeof (term));

  term.c_cflag = CREAD | CS8;
  term.c_cc[VMIN] = 1;

  cfsetispeed (&term, B115200);
  cfsetospeed (&term, B115200);

  tcsetattr (fd, TCSANOW, &term);

  /* Flush input buffer.  */
  int oldfl = fcntl (fd, F_GETFL);
  fcntl (fd, F_SETFL, oldfl | O_NONBLOCK);
  while (read (fd, &c, 1) != -1);
  fcntl (fd, F_SETFL, oldfl);

  asprintf (&command, "%s\r", argv[2]);
  for (i = 0; i < strlen (command); i++)
    write (fd, &command[i], 1);

  /* Suck our local echo.  */
  asprintf (&expected_reply, "%s\r\n", command);
  for (i = 0; i < strlen (expected_reply);)
    {
      read (fd, &c, 1);
      if (c == expected_reply[i])
	i++;
    }

  free (expected_reply);
  asprintf (&expected_reply, "\r\n");
  for (i = 0; i < strlen (expected_reply);)
    {
      read (fd, &c, 1);
      if (c == expected_reply[i])
	i++;
      else
	putchar (c);
    }
  putchar ('\n');

  free (command);
  free (expected_reply);

  close (fd);

  return 0;
}
