#include <exec/types.h>
#include <stdio.h>
#include <exec/ports.h>
#include <exec/memory.h>
#include <libraries/dos.h>
#include <libraries/dosextens.h>
#include <rexx/storage.h>
#include <stdlib.h>
#include <string.h>

#include <link/io.h>

#include <proto/exec.h>
#include <proto/dos.h>
#include <proto/dlg.h>
#include <pragmas/dlg.h>

#include <private/Version.h>
#define  ObjRev "1"
const UBYTE version[]="\0$VER: DMC " BUILDVER "." ObjRev " ©" COPYRIGHT " by Digerati Dreams "__AMIGADATE__;

/*-------------------------------------------------------------------------*/

BPTR sout = NULL;

long SendRexx(TEXT *,char *);
long __stack = 50000L;

struct Library *DLGBase = NULL;


/// Main
main(int argc, char *argv[])
{
   LONG  retval;
   char buf[255];
   int i;
   
   sout = Output();

   DLGBase = OpenLibrary("dlg.library",4L);

   if (argc<2)
   {
      AFPrintf(NULL,sout,"Usage: %s <command string>\n", argv[0]);
      return;
   }
   
   strcpy(buf,"");
   
   for(i=1;i<argc;i++)
   {
      strcat(buf,argv[i]);
      strcat(buf," ");
   }
   
   buf[strlen(buf)-1]=NULL;

   retval=SendRexx(buf,argv[0]);

   if (retval!=-1)
   {
      exit(retval);
   }
   else
   {
      AFPrintf(NULL,sout,"%s failed.\n", argv[0]);
      exit(10);
   }
}
//-

/// SendRexx
long SendRexx(TEXT *string,char *progname)
{
   struct RexxMsg *RexxMess;
   struct RexxArg *ra;

   struct MsgPort *RexxPort;
   struct MsgPort *ReplyPort;
   long  retval = 10;

   if (ReplyPort=CreatePort(0,0))
   {
      RexxMess = calloc(1,sizeof(struct RexxMsg));

      if(RexxMess)
      {
         RexxMess->rm_Node.mn_ReplyPort=ReplyPort;
         RexxMess->rm_Node.mn_Length=sizeof(struct RexxMsg);
         RexxMess->rm_Action=RXCOMM | RXFF_RESULT;
         RexxMess->rm_Args[0]=string;

         Forbid();

         RexxPort=FindPort("DLGM_ARexx");

         if (RexxPort)
            PutMsg(RexxPort, (struct Message *) RexxMess);

         Permit();

         if(RexxPort)
         {
            WaitPort(ReplyPort);
            GetMsg(ReplyPort);
            retval=RexxMess->rm_Result1;

            if(RexxMess->rm_Result2)
            {
               AFPrintf(NULL,sout,"[32m%s",RexxMess->rm_Result2);

               if(retval)
               {
                  AFPrintf(NULL,sout," %ld[0m\n",retval);
               }
               else
               {
                  AFPrintf(NULL,sout,"[0m\n");
               }
               
               ra=(struct RexxArg *)((char *)RexxMess->rm_Result2 - &( (struct RexxArg *)NULL)->ra_Buff[0]);
               FreeMem(ra, ra->ra_Size);
            }
         }
         else
         {
            AFPrintf(NULL,sout,"%s: No [%s] ARexx port available\n",progname,"DLGM_ARexx");
            retval=11;
         }
         free(RexxMess);
      }
      DeletePort(ReplyPort);
   }
   return retval;
}
//-

