/*
 * File:	message.c
 *
 * Author:	Ulli Horlacher (framstag@rus.uni-stuttgart.de)
 *
 * Contrib.:	Martin Buck (Martin-2.Buck@student.uni-ulm.de)
 * 		Christoph 'GNUish' Goern (goern@janus.beuel.rhein.de)
 *
 * History:
 *  1995-08-11  Framstag	initial version
 *  1995-09-01  Framstag	added global variable prg
 *  1995-12-21  Framstag	with or without unix error message
 *  1995-02-19  mbuck		alternative message format
 *  1995-04-12  Framstag	added call to cleanup routine
 *  1997-02-14  GNUish		renamed ALT_MESSAGES to GNU_MESSAGES
 *  1997-09-21  Framstag	severity level printed in word
 *  2001-02-16  Framstag	added severity level X (without cleanup)
 *
 * VMS-like information, warning and error message routine.
 *
 * Copyright © 1995-2001 Ulli Horlacher
 * This file is covered by the GNU General Public License
 */


#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <ctype.h>

#include "globals.h"
#include "message.h"
#include "string.h"

/* exit on fatalerror flag */
extern int xonf;


/*
 * message - print information, warning and error messages on stderr
 *           ( shameless plug from VMS :-) )
 *
 * INPUT:  cmd		- command or programm which sends message
 *         severity	- severity of message
 *         text		- text of message
 *
 * exit program on a fatal 'F' (with cleanup) or exit 'X' error
 */
void message(char *cmd, char severity, const char *text) {
  char *facility;	/* facility id */
  extern char *prg;	/* name of the game */

  /* no cmd? then use global variable prg */
  if (*cmd==0) cmd=prg;

  /* strip off path */
  facility=strrchr(cmd,'/');
  if (!facility)
    facility=cmd;
  else
    facility++;

  /* print the message */
  severity=toupper(severity);
#ifdef GNU_MESSAGES
  fprintf(stderr, "%s: %s: %s", facility,
#else
  fprintf(stderr, "%%%s-%s: %s", facility,
#endif
 	   (severity == 'F') ? "Fatalerror" :
	  ((severity == 'X') ? "Fatalerror" :
	  ((severity == 'E') ? "Error" :
	  ((severity == 'W') ? "Warning" :
	  ((severity == 'I') ? "Info" : 
	                       "Unknown")))), text);
  /* fprintf(stderr,"%%%s-%c, %s",facility,severity,text); */

  /* on error print the internal error message, too */
  if ((severity=='E' || severity=='F' || severity=='X') && errno)
    fprintf(stderr," : %s",strerror(errno));
  fprintf(stderr,"\n");

  /* exit on a fatal error */
  if (toupper(severity)=='X') exit(1);
  if (toupper(severity)=='F') {
    cleanup();
    if (xonf) exit(1);
  }

}
