
#include "gerror.h"

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#ifndef WIN32
#include <unistd.h>
#else
#include "gsys/win32.h"
#endif
#include "gcomm.h"

#include "gsys/gag_trace.h"
#include "gcore-message-c.h"

/**
 * Sic version of the perror system call with call to exit.
 *
 * @param[in] s is the prefix of the message.
 */
void sic_perror( const char *s)
{
#ifndef WIN32
    char *message = errno ? strerror( errno) : "unknown error";
#else
    LPTSTR message;

    errno = GetLastError( );

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        errno,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &message,
        0, NULL );
#endif
    gag_trace( "<error> %s: %s (%d)", s, message, errno);
    errno = 0;
    gcore_c_message(seve_e, s, "pid %d: %s", sic_get_current_task_id( ), message);
#ifdef WIN32
    LocalFree( message);
#endif
    sic_do_exit( 1);
}

/**
 * Sic version of the perror system call.
 *
 * @param[in] s is the prefix of the message.
 */
void sic_pwarning( const char *s)
{
    char *message = errno ? strerror( errno) : "unknown error";
    gag_trace( "<warning> %s: %s (%d)", s, message, errno);
    errno = 0;
    gcore_c_message(seve_w, s, "pid %d: %s", sic_get_current_task_id( ), message);
}
