/**********************************************************************/
/* MSCCOMP - this file contains macros for automating the compile and */
/*  error-search procedures under Microsoft 4.0. To compile the       */
/*  current buffer, press ALT C. To search for errors, press CTRL N.  */
/*                                                                    */
/* Written by Marc Adler of MAGMA SYSTEMS.  January 1987              */
/**********************************************************************/

#define ALT_C   174
#define CTRL_N  14

#define NO      0
#define YES     1

int reached_eof;

init()
{
  assign_key("compile",    ALT_C);
  assign_key("next_error", CTRL_N);
}

compile()
{
  string currfile, extension;
  string errmsg;
  int    i;

  errmsg = "Error - the file is not a C file. <Hit ENTER to continue>";
  
  currfile = filename();

  /* Make sure that the current buffer is a C file */
  if ((i = index(currfile, ".")) > 0)           /* get the extension */
  {
    extension = substr(currfile, i+1, 3);
    if (extension != "c" || extension != "C")   /* is it a C file?   */
    {
      get_tty_str(errmsg);                      /* NO!!! Error!!!    */
      return;
    }
  }
  else              /* the buffer has no extension, so it's an error */
  {
    get_tty_str(errmsg);
    return;
  }

  writefile(currfile);      /* save the current version & compile it */
  os_command(sprintf("msc /AL /Zi /J %s; > errs", currfile));
  next_error();             /* see if there are errors               */
}

next_error()
{
  int id, old_id;
  int n;
  string cl, foo;

  old_id = currbuf();           /* save the id of the source buffer */

  if ((id = find_buffer("errs")) == 0)
  {
    id = create_buffer("errs");
    reached_eof = NO;
  }
  id = setcurrbuf(id);

  /* Microsoft C Ver.4.0 puts out error messages in this format : */
  /*      filename(line #) : messagetype error# message           */
  if (reached_eof == NO && fsearch("([0-9][0-9]*) : ?*error") > 0)
  {
    n = atoi(substr(cl = currline(), currcol()+1, 5));  /* get line # */
    gobol();                    /* move to the next error */
    if (!down())
      reached_eof = YES;
    show_buffer(old_id);        /* go to the source buffer and */
    goline(n);                  /*  move to the offending line */
    message(cl);                /* display the error message   */
    get_tty_char();             /* and let the user acknowledge*/
  }

  else          /* Reached the end of the error file */
  {
    foo = get_tty_str("NO MORE ERRORS");
    delete_buffer(id);          /* get rid of the error buffer */
    show_buffer(old_id);        /* and set the current buffer  */
  }
}
