#define INCL_PM
#define INCL_BASE
#include <os2.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <process.h>
//#include <builtin.h>


#include "wkfedit.h"   /* DDE signatures       */

/* ----------------------------------------------------------------- */
/* Function prototypes                                               */
/* ----------------------------------------------------------------- */
FNWP       fnwpClientWndProc;

VOID       ddeExecute     ( HWND hwnd, HWND hwndMsg, PDDESTRUCT pDDE );
MRESULT    ddeInitiate    ( HWND hwnd, HWND hwndMsg, PDDEINIT pDDEi );
VOID       ddeTerminate   ( HWND hwnd, HWND hwndMsg );


/* ----------------------------------------------------------------- */
/* Globals                                                           */
/* ----------------------------------------------------------------- */
CHAR szClientClass[] = "EFTE DDE daemon";
CHAR szQueueName[256] = {0};

HAB  hAB = NULLHANDLE;                              /* anchor block handle        */
HMQ  hMQ = NULLHANDLE;                              /* message queue handle       */
HWND hwndFrame = NULLHANDLE;                        /* frame window handle        */
HWND hwndClient = NULLHANDLE;                       /* client window handle       */

HWND hwndDDE = NULLHANDLE;                          /* DDE client window handle   */
CHAR szTopicName[CCHMAXPATH];                       /* DDE topic name buffer      */
CHAR szFullName[CCHMAXPATH];
PCHAR pszTopicName = NULL;

ULONG gulSession = 0;
HQUEUE gqh       = NULLHANDLE;
BOOL  gTriggered = FALSE;
CHAR gszCommandLine[2048];

VOID StartEditor(PSZ args)
{
   STARTDATA sd;
   PID   ulPid;
   APIRET rc;
   ULONG       ulData=0;
   REQUESTDATA rd;
   PRETRESULT  pr;
   BYTE prio;

   memset(&sd,0,sizeof(sd));
   sd.Length    = sizeof(sd);
   sd.Related   = SSF_RELATED_CHILD;
   sd.FgBg      = SSF_FGBG_FORE;
   sd.PgmInputs = args;
   sd.PgmName   = "eftepm.exe";
   sd.TermQ     = szQueueName;
   DosStartSession(&sd,&gulSession,&ulPid);
   DosReadQueue(gqh,&rd,&ulData,(PPVOID)&pr,0,DCWW_WAIT,&prio,NULLHANDLE);
   if (pr) {
      rc = DosFreeMem(pr);
   }
   if (!gTriggered) {
      gulSession = 0;
      WinPostMsg(hwndClient,WM_QUIT,MPVOID,MPVOID);
   } /* endif */
   gTriggered = FALSE;
   return;
}


VOID EditorThread (PVOID p)
{
   StartEditor((PSZ)p);
   return;
}



/* ----------------------------------------------------------------- */
/* main()                                                            */
/* ----------------------------------------------------------------- */

int main( int argc, char** argv )
   {
   QMSG  qMsg;
   PPIB  ppib;
   FRAMECDATA fcData={sizeof(fcData),FCF_BORDER | FCF_AUTOICON | FCF_ICON,NULLHANDLE,1};
   DosGetInfoBlocks(NULL,&ppib);

   /* --------------------------------------------------------------- */
   /* Initialize with Presentation Manager                            */
   /* --------------------------------------------------------------- */
   hAB = WinInitialize(0);
   hMQ = WinCreateMsgQueue(hAB, 0);
   WinRegisterClass( hAB, szClientClass, fnwpClientWndProc, 0L, 0 );

   hwndFrame = WinCreateWindow(  HWND_DESKTOP,
                                 WC_FRAME,
                                 szClientClass,
                                 0,0,0,0,0,
                                 HWND_DESKTOP,
                                 HWND_TOP,
                                 1,
                                 &fcData,
                                 NULL);

   hwndClient = WinCreateWindow(  hwndFrame,
                                 szClientClass,
                                 "",
                                 0,0,0,0,0,
                                 hwndFrame,
                                 HWND_TOP,
                                 FID_CLIENT,
                                 NULL,
                                 NULL);

   sprintf(szQueueName,"\\QUEUES\\EFTEDDE_%u.QUE",ppib->pib_ulpid);
   DosCreateQueue(&gqh,QUE_FIFO | QUE_CONVERT_ADDRESS,szQueueName);

   /* Fetch filename if specified */
   if( argc == 2 )
   {
      strcpy(szTopicName,argv[1]);
      if (NO_ERROR != DosQueryPathInfo(argv[1],FIL_QUERYFULLNAME,szFullName,sizeof(szFullName)-1))
      {
         strcpy( szFullName, argv[1]);
      }
      pszTopicName = szFullName;
   }

   _beginthread(EditorThread,NULL,8192,pszTopicName);

   while( WinGetMsg( hAB, &qMsg, NULLHANDLE, 0, 0 ))
      WinDispatchMsg( hAB, &qMsg );

   WinDestroyWindow( hwndFrame );
   WinDestroyMsgQueue( hMQ );
   WinTerminate( hAB );

   if (gqh) {
      DosCloseQueue(gqh);
      gqh = NULLHANDLE;
   }

   return( 0 );
   }


/* ----------------------------------------------------------------- */
/* fnwpClientWndProc()                                               */
/* ----------------------------------------------------------------- */

MRESULT fnwpClientWndProc ( HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2 )
   {
   switch( msg )
      {
      case WM_DESTROY:
           if (hwndDDE) WinDdePostMsg( hwndDDE, hwnd, WM_DDE_TERMINATE, NULL, DDEPM_RETRY );
           return MRFROMLONG(0);

      case WM_DDE_INITIATE:
           return (ddeInitiate( hwnd, HWNDFROMMP( mp1 ), PVOIDFROMMP( mp2 )));

      case WM_DDE_EXECUTE:
           // _interrupt(3);
           ddeExecute( hwnd, HWNDFROMMP( mp1 ), PVOIDFROMMP( mp2 ));
           return MRFROMLONG(0);

      case WM_DDE_TERMINATE:
           // _interrupt(3);
           ddeTerminate( hwnd, HWNDFROMMP( mp1 ));
           return MRFROMLONG(0);
      }
   return( WinDefWindowProc( hwnd, msg, mp1, mp2 ));
   }


/* ----------------------------------------------------------------- */
/* ddeExecute()                                                      */
/* ----------------------------------------------------------------- */

VOID ddeExecute( HWND hwnd, HWND hwndMsg, PDDESTRUCT pDDE )
   {
   if ( pDDE && ( hwndMsg == hwndDDE ))
      {
      /* Convert pDDE offset into a pointer to the topic field */
      /* using PM macro DDES_PSZITEMNAME */

      /* Check for "Goto" message topic */
      if( !strcmp( DDES_PSZITEMNAME( pDDE ), CV_DDEGOTO ))
         {
         PGOTODATA pvWork = (PGOTODATA) DDES_PABDATA( pDDE );

         if (gulSession)
            {
            gTriggered = TRUE;
            DosStopSession(STOP_SESSION_SPECIFIED,gulSession);
            sprintf(gszCommandLine,"-l%u,%u %s",pvWork->errorline,pvWork->erroroffset,pszTopicName);
            _beginthread(EditorThread,NULL,8192,gszCommandLine);
            } /* endif */
         }
      WinDdePostMsg( hwndDDE, hwnd, WM_DDE_ACK, pDDE, DDEPM_RETRY );
      }
   }


/* ----------------------------------------------------------------- */
/* ddeInitiate()                                                     */
/* ----------------------------------------------------------------- */

MRESULT ddeInitiate( HWND hwnd, HWND hwndMsg, PDDEINIT pDDEi )
   {
   APIRET rc;
   if ( !strcmp( CV_DDEAPPNAME, pDDEi->pszAppName )
         && (!pszTopicName || !strcmp( szTopicName, pDDEi->pszTopic ))
        )
      {
      hwndDDE = hwndMsg;
      WinDdeRespond( hwndDDE, hwnd, pDDEi->pszAppName, pDDEi->pszTopic, pDDEi->offConvContext ? (PCONVCONTEXT) ((PUCHAR)pDDEi + pDDEi->offConvContext) : NULL );
      }
   rc = DosFreeMem( pDDEi );   /* REQUIRED msj v4n3 may 89   */
   return MRFROMLONG(TRUE);
   }

/* ----------------------------------------------------------------- */
/* ddeTerminate()                                                    */
/* ----------------------------------------------------------------- */

VOID ddeTerminate( HWND hwnd, HWND hwndMsg )
   {
   if ( hwndMsg == hwndDDE )
      {
      WinDdePostMsg( hwndDDE, hwnd, WM_DDE_TERMINATE, NULL, DDEPM_RETRY );
      hwndDDE = NULLHANDLE;
      }
   }

