/*
 *                          M E S S A G E . C
 *
 *  Routines for warnings and error messages.
 *
 *  Version      : $Revision: 1.4 $
 *
 *  Created      : Thu May 19 19:32:03 1994
 *  Author       : Ulrich Drepper <drepper@mydec>
 *
 *  Last modified: Fri Jul 15 11:24:39 1994
 *  Author       : Ulrich Drepper <drepper@mydec>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 1, or (at your option)
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */
#if !defined(lint)
static const char *vcid = "$Id: message.c,v 1.4 1994/07/15 10:24:50 drepper Exp $";
#endif /* lint */

#include <stdarg.h>
#include <stdio.h>
#include <string.h>

#include "empire.h"

/* we use gcc and therefor can use the built-in alloca */
#if !defined(alloca)
# define alloca(size) __builtin_alloca(size)
#endif

/*
 * exported functions
 */
void
message(WarnLevel level, const char *fmt, ...)
{
    static const char *msgs[] = {
	"",
	"WARNING: ",
	"ERROR: ",
	"FATAL: "
    };
    va_list ap;
    int cnt         = 0;
    const char *cp  = fmt;
    char *dp;
    char *nfmt;
    const char *msg = msgs[level&127];
    int  msglen     = strlen(msg);

    /* no format string ? */
    if (!fmt) return;

    /* prepare format string: every line begins with level string */
    while (*cp)
	if (*cp++ == '\n') cnt++;

    /* prepare variable arguments */
    va_start(ap, fmt);

    if (cnt == 0 && xIsUp && !(level&128) &&
	((level&127)==WARN || (level&127)==ERROR)) {
	vsprintf(messageStr, fmt, ap);
	showMessageLine();
    } else {
	nfmt = (char*)alloca(strlen(fmt)+1+msglen*(cnt+1)+1);
	strcpy(nfmt, msg);

	for (dp=nfmt+msglen, cp=fmt; (*dp++=*cp); )
	    if (*cp++ == '\n') {
		strcpy(dp, msg);
		dp += msglen;
	    }
	*dp-- = '\0';
	*dp   = '\n';

	/* print the string in new format */
	vfprintf(stderr, nfmt, ap);

	/* test for report */
	if (level&128) {
	    fprintf(stderr, "%sPlease send a bug report to " AUTHOR "\n", msg);
	}
    
	fflush(stderr);
    }
    va_end(ap);

    /* no continuation possible for fatal error */
    if ((level&127) == FATAL) exit(1);
}

/*
 * Local Variables:
 *  mode:c
 *  c-indent-level:4
 *  c-continued-statement-offset:4
 *  c-continued-brace-offset:0
 *  c-brace-offset:0
 *  c-imaginary-offset:0
 *  c-argdecl-indent:4
 *  c-label-offset:-2
 * End:
 */
