/* hw_io.c (emx+gcc) */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/hw.h>


static void usage (void)
{
  fputs ("Usage: hw_io [-s] [-p <port>] [-a <from> <to>]\n", stderr);
  exit (1);
}


int main (int argc, char *argv[])
{
  int opt_s, i, lo, hi, port, def_range;
  unsigned char buf[256];
  char *q;

  opt_s = 0; port = 0x40; def_range = 1;
  i = 1;
  while (i < argc)
    {
      if (strcmp (argv[i], "-s") == 0)
        {
          opt_s = 1; ++i;
        }
      else if (strcmp (argv[i], "-p") == 0 && argc - i >= 2)
        {
          errno = 0;
          port = strtol (argv[i+1], &q, 0);
          if (errno != 0 || *q != 0 || port < 0 || port > 0xffff)
            usage ();
          i += 2;
        }
      else if (strcmp (argv[i], "-a") == 0 && argc - i >= 3)
        {
          errno = 0;
          lo = strtol (argv[i+1], &q, 0);
          if (errno != 0 || *q != 0)
            usage ();
          hi = strtol (argv[i+2], &q, 0);
          if (errno != 0 || *q != 0)
            usage ();
          def_range = 0;
          i += 3;
        }
      else
        usage ();
    }
  if (def_range)
    {
      lo = port; hi = port;
    }
  if (_portaccess (lo, hi) != 0)
    {
      perror ("_portaccess");
      return 1;
    }
  if (opt_s)
    for (;;)
      {
        _inps8 (port, buf, sizeof (buf));
        for (i = 0; i < sizeof (buf); ++i)
          printf ("  %.2x", buf[i]);
      }
  else
    for (;;)
      printf ("  %.2x", _inp8 (port));
  return 0;
}
