/****************************************************************************
                   Microsoft RPC Version 2.0
           Copyright Microsoft Corp. 1992, 1993, 1994- 1996
                       Hello Example

    FILE:       helloc.c

    PURPOSE:    Client side of RPC distributed application

    FUNCTIONS:  main() - binds to server and calls remote procedure

    COMMENTS:   This version of the distributed application that
                prints "hello, world" (or other string) on the server
                features a client that manages its connection to the
                server. It uses the binding handle hello_IfHandle,
                defined in the file hello.h.

****************************************************************************/

#include <windows.h>   // required for all Windows applications
#include <rpc.h>
#include "hello.h"    // header file generated by MIDL compiler
#include "hellores.h"

HINSTANCE hInst;          // current instance

char szAppName[] = "hello";   // The name of this application
char szTitle[]   = "hello"; // The title bar text

/****************************************************************************

        FUNCTION: WinMain(HINSTANCE, HINSTANCE, LPSTR, int)

        PURPOSE: calls initialization function, processes message loop
****************************************************************************/
HANDLE hAccelTable;
#define RPC_TRANSPORT_TCP       3
#define RPC_TRANSPORT_DSP       9
void  CallServer() ;
LRESULT CALLBACK WndProc(
                HWND hWnd,         // window handle
                UINT message,      // type of message
                WPARAM uParam,     // additional information
                LPARAM lParam) ;    // additional information


void RPC_ENTRY MacCallbackFunc(short *pStatus)
{
  MSG msg ;

  while (*pStatus == 1)         
  {
    if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) &&
       !TranslateAccelerator (msg.hwnd, hAccelTable, &msg)) 
    {
      TranslateMessage(&msg);
      DispatchMessage(&msg); 
    }
  }
}

int CALLBACK WinMain(
        HINSTANCE hInstance,
        HINSTANCE hPrevInstance,
        LPSTR lpCmdLine,
        int nCmdShow)
{

        MSG msg;
        unsigned long Length ;
        char Temp[128] ;

        RpcMacSetYieldInfo(MacCallbackFunc) ;

        if (!hPrevInstance) {       // Other instances of app running?
                        if (!InitApplication(hInstance)) { // Initialize shared things
                        return (FALSE);     // Exits if unable to initialize
                }
        }

        /* Perform initializations that apply to a specific instance */
        if (!InitInstance(hInstance, nCmdShow)) {
                return (FALSE);
        }

        hAccelTable = LoadAccelerators (hInstance, MAKEINTRESOURCE(IDR_HELLO));

        /* Acquire and dispatch messages until a WM_QUIT message is received. */

        while (GetMessage(&msg, // message structure
           NULL,   // handle of window receiving the message
           0,      // lowest message to examine
           0))     // highest message to examine
        {
                if (!TranslateAccelerator (msg.hwnd, hAccelTable, &msg)) {
                        TranslateMessage(&msg);// Translates virtual key codes
                        DispatchMessage(&msg); // Dispatches message to window
                }
        }

        return (msg.wParam); // Returns the value from PostQuitMessage

        lpCmdLine; // This will prevent 'unused formal parameter' warnings
}


/****************************************************************************

        FUNCTION: InitApplication(HINSTANCE)

        PURPOSE: Initializes window data and registers window class

        COMMENTS:

                This function is called at initialization time only if no other
                instances of the application are running.  This function performs
                initialization tasks that can be done once for any number of running
                instances.

                In this case, we initialize a window class by filling out a data
                structure of type WNDCLASS and calling the Windows RegisterClass()
                function.  Since all instances of this application use the same window
                class, we only need to do this when the first instance is initialized.


****************************************************************************/

BOOL InitApplication(HINSTANCE hInstance)
{
        WNDCLASS  wc;

        // Fill in window class structure with parameters that describe the
        // main window.

        wc.style         = CS_HREDRAW | CS_VREDRAW;// Class style(s).
        wc.lpfnWndProc   = (WNDPROC)WndProc;       // Window Procedure
        wc.cbClsExtra    = 0;                      // No per-class extra data.
        wc.cbWndExtra    = 0;                      // No per-window extra data.
        wc.hInstance     = hInstance;              // Owner of this class
        wc.hIcon         = NULL ;// LoadIcon (hInstance, MAKEINTRESOURCE(IDI_APP)); // Icon name from .RC
        wc.hCursor       = LoadCursor(NULL, IDC_ARROW);// Cursor
        wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);// Default color
        wc.lpszMenuName  = MAKEINTRESOURCE(IDR_HELLO); // Menu from .RC
        wc.lpszClassName = szAppName;              // Name to register as

        // Register the window class and return success/failure code.
        return (RegisterClass(&wc));
}


/****************************************************************************

        FUNCTION:  InitInstance(HINSTANCE, int)

        PURPOSE:  Saves instance handle and creates main window

        COMMENTS:

                This function is called at initialization time for every instance of
                this application.  This function performs initialization tasks that
                cannot be shared by multiple instances.

                In this case, we save the instance handle in a static variable and
                create and display the main program window.

****************************************************************************/

BOOL InitInstance(
        HINSTANCE          hInstance,
        int             nCmdShow)
{
        HWND            hWnd; // Main window handle.

        // Save the instance handle in static variable, which will be used in
        // many subsequence calls from this application to Windows.

        hInst = hInstance; // Store instance handle in our global variable

        // Create a main window for this application instance.

        hWnd = CreateWindowEx(
#ifdef _MAC
                WS_EX_FORCESIZEBOX,  // Make sure we get a sizebox
#else
                0,                     // No extended styles needed for Windows
#endif
                szAppName,           // See RegisterClass() call.
                szTitle,             // Text for window title bar.
                WS_OVERLAPPEDWINDOW,// Window style.
                CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, // Use default positioning
                NULL,                // Overlapped windows have no parent.
                NULL,                // Use the window class menu.
                hInstance,           // This instance owns this window.
                NULL                 // We don't use any data in our WM_CREATE
        );

        // If window could not be created, return "failure"
        if (!hWnd) {
                return (FALSE);
        }

        // Make the window visible; update its client area; and return "success"
        ShowWindow(hWnd, nCmdShow); // Show the window
        UpdateWindow(hWnd);         // Sends WM_PAINT message

        return (TRUE);              // We succeeded...

}

static HWND hwndEdit ;

void _cdecl PrintToConsole(LPCSTR lpszFormat, ...)
{
    char szBuffer[512] ;
    int nBuf ;

    nBuf = wvsprintf((LPSTR) szBuffer, lpszFormat, ((LPBYTE) &lpszFormat)+sizeof(lpszFormat)) ;
    
    if(hwndEdit)
    {
        SendMessage(hwndEdit, EM_SETSEL, (WPARAM) (INT) -1, (LPARAM) (INT) -1) ;
        SendMessage(hwndEdit, EM_REPLACESEL, 0, (LPARAM) (LPCTSTR) szBuffer) ;
    }
}

/****************************************************************************

        FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)

        PURPOSE:  Processes messages

        MESSAGES:

        WM_COMMAND    - application menu (About dialog box)
        WM_DESTROY    - destroy window

        COMMENTS:

        To process the IDM_ABOUT message, call MakeProcInstance() to get the
        current instance address of the About() function.  Then call Dialog
        box which will create the box according to the information in your
        hello.rc file and turn control over to the About() function.  When
        it returns, free the intance address.

****************************************************************************/

LRESULT CALLBACK WndProc(
                HWND hWnd,         // window handle
                UINT message,      // type of message
                WPARAM uParam,     // additional information
                LPARAM lParam)     // additional information
{
        int wmId, wmEvent;
        FARPROC lpProcSettings;  

        switch (message) {
                case WM_CREATE:
                        hwndEdit = CreateWindow("edit", NULL, 
                                WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL |
                                WS_BORDER | ES_LEFT | ES_MULTILINE | ES_AUTOHSCROLL |
                                ES_AUTOVSCROLL, 0, 0, 0, 0, hWnd, hInst, // 1, 
                                (HINSTANCE) (((LPCREATESTRUCT) lParam) -> hInstance), NULL) ;
                        return 0 ;

                case WM_SETFOCUS:
                        SetFocus(hwndEdit) ;
                        return 0 ;

                case WM_SIZE:
                        MoveWindow(hwndEdit, 0, 0, LOWORD(lParam), HIWORD(lParam), TRUE) ;
                        return 0 ;
#ifdef _MAC
                case WM_SYSCOMMAND:    // About menu item is in the sysmenu for Macintosh
#endif
                case WM_COMMAND:  // message: command from application menu

                        wmId    = LOWORD(uParam);
                        wmEvent = HIWORD(uParam);

                        switch (wmId) {
                           case IDM_EXIT:
                                   DestroyWindow (hWnd);
                                   break;

                           case ID_CALLSERVER:
                              CallServer() ;
                              break;

                           default:
                                   return (DefWindowProc(hWnd, message, uParam, lParam));
                        }
                        break;

                case WM_DESTROY:  // message: window being destroyed
                        PostQuitMessage(0);
                        break;

                default:          // Passes it on if unproccessed
                        return (DefWindowProc(hWnd, message, uParam, lParam));
        }
        return (0);
}

void  CallServer()
{
    RPC_STATUS status;
    unsigned char * pszUuid             = NULL;
    unsigned char * pszProtocolSequence = "ncacn_at_dsp";
    unsigned char * pszNetworkAddress   = "hostname" ;
    unsigned char * pszEndpoint         = "hello";
    unsigned char * pszOptions          = NULL;
    unsigned char * pszStringBinding    = NULL;
    unsigned char * pszString           = "hello, world";
    unsigned long ulCode;
    int i;

    /* Use a convenience function to concatenate the elements of */
    /* the string binding into the proper sequence.              */
    status = RpcStringBindingCompose(pszUuid,
                                     pszProtocolSequence,
                                     pszNetworkAddress,
                                     pszEndpoint,
                                     pszOptions,
                                     &pszStringBinding);
    PrintToConsole("RpcStringBindingCompose returned 0x%x\r\n", status);
    PrintToConsole("pszStringBinding = %s\r\n", pszStringBinding);
    if (status) {
        exit(status);
    }

    /* Set the binding handle that will be used to bind to the server. */
    status = RpcBindingFromStringBinding(pszStringBinding,
                                         &hello_IfHandle);
    PrintToConsole("RpcBindingFromStringBinding returned 0x%x\r\n", status);
    if (status) {
        exit(status);
    }

    PrintToConsole("Calling the remote procedure 'HelloProc'\r\n");
    PrintToConsole("Print the string '%s' on the server\r\n", pszString);

    RpcTryExcept {
        HelloProc(pszString);  // make call with user message
        PrintToConsole("Calling the remote procedure 'Shutdown'\r\n");
        Shutdown();  // shut down the server side
    }
    RpcExcept(1) {
        ulCode = RpcExceptionCode();
        PrintToConsole("Runtime reported exception 0x%lx = %ld\r\n", ulCode, ulCode);
    }
    RpcEndExcept

    /*  The calls to the remote procedures are complete. */
    /*  Free the string and the binding handle           */
    status = RpcStringFree(&pszStringBinding);  // remote calls done; unbind
    PrintToConsole("RpcStringFree returned 0x%x\r\n", status);
    if (status) {
        exit(status);
    }

    status = RpcBindingFree(&hello_IfHandle);  // remote calls done; unbind
    PrintToConsole("RpcBindingFree returned 0x%x\r\n", status);
}  // end main()

/* end file helloc.c */
