#include "stormerrhandling.h"
#include <stdio.h>
#include <string.h>
#include <proto/exec.h>
#include <proto/rexxsyslib.h>


char *errportname = NULL;
char *errportfile = NULL;
char *errportsource = NULL;
int errportline = -1;
int errportkind = ERRKIND_MESSAGE;

static char stringbuffer[4096];


void stormMessage(char *errstr)
{
    if(errportname)
    {
        struct MsgPort *replyPort;

        sprintf(stringbuffer, "ERROR 0 MODE 20 STRINGS \"%s\"", errstr);
        if(errportfile) sprintf(stringbuffer + strlen(stringbuffer), " FILE \"%s\"", errportfile);
        if(errportline >= 0) sprintf(stringbuffer + strlen(stringbuffer), " LINE %d", errportline);
        if(errportsource) sprintf(stringbuffer + strlen(stringbuffer), " SOURCE \"%s\"", errportsource);

        errportfile = NULL;
        errportsource = NULL;
        errportline = -1;
        errportkind = ERRKIND_MESSAGE;

        replyPort = CreateMsgPort();
        if(replyPort)
        {
            struct RexxMsg *msg = CreateRexxMsg(replyPort, NULL, NULL);
            if(msg)
            {
                if(msg->rm_Args[0] = CreateArgstring(stringbuffer, strlen(stringbuffer)))
                {
                    struct MsgPort *sendPort;

                    Forbid();
                    if(sendPort = FindPort(errportname))
                    {
                        PutMsg(sendPort, (struct Message*)msg);
                        Permit();

                        WaitPort(replyPort);
                        while(GetMsg(replyPort));
                    }
                    else
                    {
                        Permit();
                    }
                    DeleteArgstring(msg->rm_Args[0]);
                }
                DeleteRexxMsg(msg);
            }
            DeleteMsgPort(replyPort);
        }
    }
}


