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

#define INCL_DOSPROCESS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <process.h>
#include <os2.h>

static void dump_tib (void)
{
  PTIB ptib;
  PPIB ppib;

  if (DosGetInfoBlocks (&ptib, &ppib) == 0)
    {
      printf ("Stack base: %.8lx\n", (long)ptib->tib_pstack);
      printf ("Stack limit: %.8lx\n", (long)ptib->tib_pstacklimit);
      printf ("Priority: %.8lx\n", (long)ptib->tib_ptib2->tib2_ulpri);
    }
}


int main (int argc, char *argv[])
{
  ULONG rc;
  int i, arg0, len, verbose;
  char *p;

  arg0 = 1; verbose = 0;
  if (arg0 < argc && strcmp (argv[arg0], "-v") == 0)
    {
      verbose = 1;
      ++arg0;
    }
  if (arg0 < argc && strcmp (argv[arg0], "-t") == 0)
    {
      verbose = 2;
      ++arg0;
    }
  if (arg0 >= argc)
    {
      printf ("Usage: idle <command>\n");
      return 1;
    }
  if (verbose >= 2)
    dump_tib ();
  rc = DosSetPriority (PRTYS_PROCESS, PRTYC_IDLETIME, 0, 0);
  if (verbose >= 2)
    dump_tib ();
  if (rc != 0)
    {
      fprintf (stderr, "DosSetPriority failed, rc=%lu\n", rc);
      return 2;
    }
  len = 1;
  for (i = arg0; i < argc; ++i)
    len += strlen (argv[i]) + 1;
  p = malloc (len);
  if (p == NULL)
    {
      perror ("malloc");
      return 2;
    }
  *p = 0;
  for (i = arg0; i < argc; ++i)
    {
      if (i > arg0)
        strcat (p, " ");
      strcat (p, argv[i]);
    }
  i = system (p);
  if (i < 0)
    {
      perror ("system");
      return 2;
    }
  else if (verbose >= 1)
    printf ("Return code = %d\n", i);
  return i;
}
