/* Copyright 1989, 1990 by James Aspnes, David Applegate, and Bennet Yee */
/* See the file COPYING for distribution information */
#include <stdio.h>

#include "db.h"
#include "config.h"
#include "externs.h"

datum me;
datum you;
datum text = NOTHING;
datum mtext = NOTHING;

int please_gc = 0;
int please_checkpoint = 0;
int shutdown_flag = 0;

/* get a line of input, massaging it appropriately... */
/* I recognize, deep in my heart, that this code is cruft */
static const char *get_line (char *buf, int len)
{
  int c;
  char *p;

  p = buf;

  while (p < buf + len - 2) {
    if ((c = getchar ()) == EOF)
      return 0;
    if (c == '\n') {
      if ((c = getchar ()) == '\n') {
        break;
      } else if (c == '-') {
        ungetc (c, stdin);
        break;
      } else if (c == EOF) {
        break;
      }
      *p++ = '\t';
    }
#ifdef WIN32
    if (c == '\r') continue; // Skip Windows cruft
#endif
    *p++ = c;
  }

  *p = '\0';
  return buf;
}

static void command_loop (datum obj)
{
  char buf[MAX_STRLEN + 1];
  struct object *o;
  object_flag_type old_flags = 0;

  buf[0] = RUN_CODE_COMMAND;

  /* set obj to be connected */
  if ((o = object (obj)) != 0) {
    old_flags = o->flags;
    o->flags |= F_CONNECTED;
  }

  while (get_line (buf + 1, MAX_STRLEN - 1) != 0) {
    if (buf[1] == '-') {
      /* regular command */
      parse_command (obj, buf + 2);
    } else {
      parse_command (obj, buf);
    }
  }

  if ((o = object (obj)) != 0) {
    o->flags = old_flags;
  }
}

void notify (datum player, const char *t)
{
  printf ("%ld: %s\n", player, t);
  fflush (stdout);
}

int main (int argc, char **argv)
{
  FILE *f;
  datum obj;

  if (argc < 3) {
    fprintf (stderr, "Usage: %s infile outfile [object]\n", *argv);
    return (1);
  }

  /* ok, read it in */
  if ((f = fopen (argv[1], "rb")) == NULL || db_read (f) < 0) {
    fprintf (stderr, "Couldn't load %s!\n", argv[1]);
    return (2);
  }
  fclose (f);

  if (argc < 4) {
    obj = TOP_OBJECT;
  } else {
    obj = atoi (argv[3]);
  }

  command_loop (obj);

  /* clear up any garbage */
  full_gc ();

  /* write it out */
  if ((f = fopen (argv[2], "wb")) == NULL || db_write (f) < 0 ||
    fclose (f) < 0) {
    fprintf (stderr, "Couldn't write %s\n", argv[2]);
  }

  return (0);
}