/* Copyright 1996 Acorn Computers Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* error.c: ANSI draft (X3J11 May 86) code (various error routines) */
/* Copyright (C) A.C. Norman and A. Mycroft */
/* version 0.01b */

#include "hostsys.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <signal.h>
#include <assert.h>  /* for __assert() */
#include <string.h>  /* for strerror */
#include <errno.h>

extern int _fprintf_lf(FILE *fp, const char *fmt, ...);
extern int _sprintf_lf(char *buff, const char *fmt, ...);

void _sysdie(const char *s)
{
    char v[200];
    char *cs, *ct;

    cs = v;
    ct = _kernel_getmessage("*** fatal error in run time system: ", "C33");
    while ((*cs++ = *ct++) >= ' ');
    cs--;
    ct = (char *)s;
    while ((*cs++ = *ct++) >= ' ');
    _sys_msg(v);
    exit(1);
}

/* from <assert.h> */
void __assert(char *expr, char *file, int line)
{
    _fprintf_lf(stderr,
                _kernel_getmessage("*** assertion failed: %s, file %s, line %d", "C34"),
                expr, file, line);
    fputc('\n', stderr);
    abort();
}

/* from <string.h> */
char *strerror(int n)
{
    static char v[80];
    char *s, *t;

    switch (n)
    {   case 0:
            t = "C35";
#ifdef DEFAULT_TEXT
            s = "No error (errno = 0)";
#endif
            break;
        case EDOM:
            t = "C36";
#ifdef DEFAULT_TEXT
            s = "EDOM - function argument out of range";
#endif
            break;
        case ERANGE:
            t = "C37";
#ifdef DEFAULT_TEXT
            s = "ERANGE - function result not representable";
#endif
            break;
        case ESIGNUM:
            t = "C66";
#ifdef DEFAULT_TEXT
            s = "ESIGNUM - illegal signal number to signal() or raise()";
#endif
            break;
        default:
            t = "C38";
#ifdef DEFAULT_TEXT
            s = "Error code (errno) %d has no associated message";
#endif
            break;
    }
    s = _kernel_getmessage(s, t);
    _sprintf_lf(v, s, n);
    return v;
}

/* from <stdio.h> */
void perror(const char *s)
{   if (s != 0 && *s != 0) fprintf(stderr, "%s: ", s);
    fprintf(stderr, "%s\n", strerror(errno));
}

/* end of error.c */