/* WIDE AREA INFORMATION SERVER SOFTWARE:
   No guarantees or restrictions.  See the readme file for the full standard
   disclaimer.

   Morris@think.com
*/

/* panic is an error system interface.  On the Mac, it will pop
 * up a little window to explain the problem.
 * On a unix box, it will print out the error and call perror()
 */
 
#include "panic.h"
#include "futil.h"

#include <ctype.h>

#ifdef ANSI_LIKE
#include <stdarg.h>
#else	
#include <varargs.h>
#endif

#ifndef EXIT_FAILURE  /* should be in stdlib */
#define EXIT_FAILURE (-1)
#endif /* ndef EXIT_FAILURE */

/*----------------------------------------------------------------------*/

static void exitAction _AP((long error));

static void
exitAction(error)
long error;
{
  long i;
#ifdef THINK_C
  Debugger();
#else
  for (i = 0; i < 100000; i++)
    ;
#endif
  abort();
}

/*----------------------------------------------------------------------*/

#define PANIC_HEADER "Fatal Error:  "
#define BELL "\007"

#ifdef ANSI_LIKE /* use ansi varargs */

#ifdef THINK_C /* pop up a dialog box */
#include "CDynamicError.h"
#endif

void
panic(format)
char* format;
{
  va_list ap;			/* the variable arguments */

#ifdef THINK_C			/* pop up a dialog box */

  char buffer[1000];		/* hope this is enough space! */
  long i;
  strncpy(buffer,PANIC_HEADER,1000);
  SysBeep(5);
  va_start(ap, format);		/* init ap */
  vsprintf(buffer + strlen(PANIC_HEADER),format,ap);
  va_end(ap);			/* free ap */
  for (i = 0L; buffer[i] != '\0'; i++)
    { if (buffer[i] == '\n' || buffer[i] == '\r')
	buffer[i] = ' ';
      }
  gError->PostAlertMessage(buffer);

#else				/* print in the shell window */

  fprintf(stderr,PANIC_HEADER);
  /* fprintf(stderr,BELL); taken out by brewster 7/91 */
  va_start(ap, format);		/* init ap */
  vfprintf(stderr,format,ap);	/* print the contents */
  va_end(ap);			/* free ap */
  fflush(stderr);

#endif
  
  exitAction(0);
}

#else /* use k&r varargs */

void
panic(va_alist)
va_dcl
{
  va_list ap;			/* the variable arguments */
  char* format;
  
  fprintf(stderr,PANIC_HEADER);
  /* fprintf(stderr,BELL); taken out by brewster 7/91 */
  
  va_start(ap);		/* init ap */

  format = va_arg(ap,char*); /* get the format */

#ifdef BSD /* some folks can't do vfprintf */
  printf("%s",format); /* just print the first thing */
#else
  vfprintf(stderr,format,ap);	/* print the contents */
#endif

  va_end(ap);		/* free ap */

  fprintf(stderr,"\n");
  fflush(stderr);

  exitAction(0);
}
  
#endif

/*----------------------------------------------------------------------*/
