//-----------------------------------------------------------------------------
// File: VoiceGroup.cpp
//
// Desc: The main file for VoiceGroup that shows how use DirectPlay along 
//       with DirectPlayVoice to allow talking in to a specific group
//       of players.
//
// Copyright (c) 1999-2001 Microsoft Corp. All rights reserved.
//-----------------------------------------------------------------------------
#define STRICT
#include <windows.h>
#include <basetsd.h>
#include <stdio.h>
#include <dxerr9.h>
#include <dplay8.h>
#include <dplobby8.h>
#include <dvoice.h>
#include <commctrl.h>
#include <cguid.h>
#include "NetConnect.h"
#include "NetVoice.h"
#include "DXUtil.h"
#include "resource.h"




//-----------------------------------------------------------------------------
// Player context locking defines
//-----------------------------------------------------------------------------
CRITICAL_SECTION g_csPlayerContext;
#define PLAYER_LOCK()                   EnterCriticalSection( &g_csPlayerContext ); 
#define PLAYER_ADDREF( pPlayerInfo )    if( pPlayerInfo ) pPlayerInfo->lRefCount++;
#define PLAYER_RELEASE( pPlayerInfo )   if( pPlayerInfo ) { pPlayerInfo->lRefCount--; if( pPlayerInfo->lRefCount <= 0 ) SAFE_DELETE( pPlayerInfo ); } pPlayerInfo = NULL;
#define PLAYER_UNLOCK()                 LeaveCriticalSection( &g_csPlayerContext );


//-----------------------------------------------------------------------------
// Defines, and constants
//-----------------------------------------------------------------------------
#define DPLAY_SAMPLE_KEY        TEXT("Software\\Microsoft\\DirectX DirectPlay Samples")
#define MAX_GROUPS              5
#define MAX_PLAYER_NAME         14
#define WM_APP_DISPLAY_PLAYERS  (WM_APP + 0)
#define VOICEGROUP_PORT         2513

// This GUID allows DirectPlay to find other instances of the same game on
// the network.  So it must be unique for every game, and the same for 
// every instance of that game.  // {9F2DA206-D197-4871-AD1D-D12F59058B5B}
GUID g_guidApp = { 0x9f2da206, 0xd197, 0x4871, { 0xad, 0x1d, 0xd1, 0x2f, 0x59, 0x5, 0x8b, 0x5b } };

struct PLAYER_STATE
{
    DWORD        dwGroup;                          // Group # that player joined in
    DWORD        dwTarget;                         // Group # that player is targeting 
};

struct APP_PLAYER_INFO
{
    LONG         lRefCount;                        // Ref count so we can cleanup when all threads 
                                                   // are done w/ this object
    DPNID        dpnidPlayer;                      // dpnid of the player
    BOOL         bTalking;                         // Is the player talking
    BOOL         bHalfDuplex;                      // If true, then player cannot talk
    PLAYER_STATE ps;                               // State of player
    TCHAR        strPlayerName[MAX_PLAYER_NAME];   // Player name
};




//-----------------------------------------------------------------------------
// App specific DirectPlay messages and structures 
//-----------------------------------------------------------------------------
#define GAME_MSGID_PLAYERSTATECHANGE   1

// Change compiler pack alignment to be BYTE aligned, and pop the current value
#pragma pack( push, 1 )

struct GAMEMSG_GENERIC
{
    DWORD dwType;
};

struct GAMEMSG_PLAYERSTATECHANGE : public GAMEMSG_GENERIC
{
    PLAYER_STATE ps;
};

// Pop the old pack alignment
#pragma pack( pop )



//-----------------------------------------------------------------------------
// Global variables
//-----------------------------------------------------------------------------
IDirectPlay8Peer*  g_pDP                         = NULL;    // DirectPlay peer object
CNetConnectWizard* g_pNetConnectWizard           = NULL;    // Connection wizard
CNetVoice*         g_pNetVoice                   = NULL;    // DirectPlay voice helper class
IDirectPlay8LobbiedApplication* g_pLobbiedApp    = NULL;    // DirectPlay lobbied app 
BOOL               g_bWasLobbyLaunched           = FALSE;   // TRUE if lobby launched
HINSTANCE          g_hInst                       = NULL;    // HINST of app
HWND               g_hDlg                        = NULL;    // HWND of main dialog
TCHAR              g_strAppName[256]             = TEXT("VoiceGroup");
APP_PLAYER_INFO*   g_pPlayerLocal                = NULL;    // APP_PLAYER_INFO* of local player
BOOL               g_bVoiceSessionInProgress     = FALSE;   // True if voice has been init'ed
DPNID*             g_pPlayers                    = NULL;    // Array of DPNIDs
DWORD              g_dwPlayersArraySize          = 0;       // Size of g_pPlayers
HRESULT            g_hrDialog;                              // Exit code for app 
TCHAR              g_strLocalPlayerName[MAX_PATH];          // Local player name
TCHAR              g_strSessionName[MAX_PATH];              // Session name
TCHAR              g_strPreferredProvider[MAX_PATH];        // Provider string
BOOL               g_bHostPlayer                 = FALSE;   // TRUE if local player is host
DPNID              g_LocalPlayerDPNID            = 0;       // DPNID of local player
DPNID              g_HostPlayerDPNID             = 0;       // DPNID of host player
DPNID              g_LocalGroupDPNID             = 0;       // DPNID of the group of the local player
GUID               g_guidDVSessionCT;                       // GUID for choosen voice compression
DVCLIENTCONFIG     g_dvClientConfig;                        // Voice client config




//-----------------------------------------------------------------------------
// Function-prototypes
//-----------------------------------------------------------------------------
INT_PTR CALLBACK VoiceDlgProc( HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam );
HRESULT          OnInitDialog( HWND hDlg );
HRESULT WINAPI   DirectPlayMessageHandler( PVOID pvUserContext, DWORD dwMessageId, PVOID pMsgBuffer );
HRESULT WINAPI   DirectPlayLobbyMessageHandler( PVOID pvUserContext, DWORD dwMessageId, PVOID pMsgBuffer );
HRESULT WINAPI   DirectPlayVoiceClientMessageHandler( PVOID pvUserContext, DWORD dwMessageId, PVOID pMsgBuffer );
HRESULT WINAPI   DirectPlayVoiceServerMessageHandler( PVOID pvUserContext, DWORD dwMessageId, PVOID pMsgBuffer );
void             SetPlayerTalking( APP_PLAYER_INFO *pPlayerInfo, BOOL bTalking );
INT_PTR CALLBACK VoiceConfigDlgProc( HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam );
HRESULT          VoiceConfigEnumCompressionCodecs( HWND hDlg );
VOID             VoiceConfigDlgOnOK( HWND hDlg );
HRESULT          InitDirectPlay();
HRESULT          DisplayPlayersInChat( HWND hDlg );
HRESULT          SendLocalStateToAll( HWND hDlg );
HRESULT          SetGroupAndTarget();
HRESULT          RefreshStatusBarText( DPNID idLocal, DPNID idHost );
HRESULT          GetHostnamePortString( TCHAR* str, LPDIRECTPLAY8ADDRESS pAddress, DWORD dwBufferLen );




//-----------------------------------------------------------------------------
// Name: WinMain()
// Desc: Entry point for the application.  Since we use a simple dialog for 
//       user interaction we don't need to pump messages.
//-----------------------------------------------------------------------------
INT APIENTRY WinMain( HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR pCmdLine, 
                      INT nCmdShow )
{
    HRESULT hr;
    HKEY    hDPlaySampleRegKey;
    BOOL    bConnectSuccess = FALSE;

    g_hInst = hInst;
    InitializeCriticalSection( &g_csPlayerContext );

    // Init player ID array 
    g_dwPlayersArraySize = 10;
    g_pPlayers = (DPNID*) malloc( sizeof(DPNID)*g_dwPlayersArraySize );

    // Read persistent state information from registry
    RegCreateKeyEx( HKEY_CURRENT_USER, DPLAY_SAMPLE_KEY, 0, NULL,
                    REG_OPTION_NON_VOLATILE, KEY_READ | KEY_WRITE, NULL, 
                    &hDPlaySampleRegKey, NULL );
    DXUtil_ReadStringRegKeyCch( hDPlaySampleRegKey, TEXT("Player Name"), 
                                g_strLocalPlayerName, MAX_PATH, TEXT("TestPlayer") );
    DXUtil_ReadStringRegKeyCch( hDPlaySampleRegKey, TEXT("Session Name"), 
                                g_strSessionName, MAX_PATH, TEXT("TestGame") );
    DXUtil_ReadStringRegKeyCch( hDPlaySampleRegKey, TEXT("Preferred Provider"), 
                                g_strPreferredProvider, MAX_PATH, TEXT("DirectPlay8 TCP/IP Service Provider") );

    InitCommonControls();

    // Init COM so we can use CoCreateInstance
    CoInitializeEx( NULL, COINIT_MULTITHREADED );

    // Create helper class
    g_pNetConnectWizard = new CNetConnectWizard( hInst, NULL, g_strAppName, &g_guidApp );
    g_pNetVoice         = new CNetVoice( DirectPlayVoiceClientMessageHandler, DirectPlayVoiceServerMessageHandler );

    if( FAILED( hr = InitDirectPlay() ) )
    {
        DXTRACE_ERR_MSGBOX( TEXT("InitDirectPlay"), hr );
        MessageBox( NULL, TEXT("Failed initializing IDirectPlay8Peer. ")
                    TEXT("The sample will now quit."),
                    TEXT("DirectPlay Sample"), MB_OK | MB_ICONERROR );
        return FALSE;
    }

    // Check if we were launched from a lobby client
    if( g_bWasLobbyLaunched && g_pNetConnectWizard->HaveConnectionSettingsFromLobby() )
    {
        // If were lobby launched then DPL_MSGID_CONNECT has already been
        // handled, so we can just tell the wizard to connect to the lobby
        // that has sent us a DPL_MSGID_CONNECT msg.
        if( FAILED( hr = g_pNetConnectWizard->ConnectUsingLobbySettings() ) )
        {
            DXTRACE_ERR_MSGBOX( TEXT("ConnectUsingLobbySettings"), hr );
            MessageBox( NULL, TEXT("Failed to connect using lobby settings. ")
                        TEXT("The sample will now quit."),
                        TEXT("DirectPlay Sample"), MB_OK | MB_ICONERROR );

            bConnectSuccess = FALSE;
        }
        else
        {
            // Read information from g_pNetConnectWizard
            _tcsncpy( g_strLocalPlayerName, g_pNetConnectWizard->GetPlayerName(), MAX_PATH-1 );
            g_strLocalPlayerName[ MAX_PATH-1 ] = 0;

            g_bHostPlayer = g_pNetConnectWizard->IsHostPlayer();

            bConnectSuccess = TRUE; 
        }
    }
    else
    {
        // If not lobby launched, prompt the user about the network 
        // connection and which session they would like to join or 
        // if they want to create a new one.

        // Setup connection wizard
        g_pNetConnectWizard->SetPlayerName( g_strLocalPlayerName );
        g_pNetConnectWizard->SetSessionName( g_strSessionName );
        g_pNetConnectWizard->SetPreferredProvider( g_strPreferredProvider );
        g_pNetConnectWizard->SetDefaultPort( VOICEGROUP_PORT );

        // Do the connection wizard
        hr = g_pNetConnectWizard->DoConnectWizard( FALSE );        
        if( FAILED( hr ) ) 
        {
            DXTRACE_ERR_MSGBOX( TEXT("DoConnectWizard"), hr );
            MessageBox( NULL, TEXT("Multiplayer connect failed. ")  
                        TEXT("The sample will now quit."),
                        TEXT("DirectPlay Sample"), MB_OK | MB_ICONERROR );
            bConnectSuccess = FALSE;
        } 
        else if( hr == NCW_S_QUIT ) 
        {
            // The user canceled the Multiplayer connect, so quit 
            bConnectSuccess = FALSE;
        }
        else
        {
            bConnectSuccess = TRUE; 

            // Read information from g_pNetConnectWizard
            _tcsncpy( g_strLocalPlayerName, g_pNetConnectWizard->GetPlayerName(), MAX_PATH-1 );
            g_strLocalPlayerName[ MAX_PATH-1 ] = 0;

            _tcsncpy( g_strSessionName, g_pNetConnectWizard->GetSessionName(), MAX_PATH-1 );
            g_strSessionName[ MAX_PATH-1 ] = 0;

            _tcsncpy( g_strPreferredProvider, g_pNetConnectWizard->GetPreferredProvider(), MAX_PATH-1 );
            g_strPreferredProvider[ MAX_PATH-1 ] = 0;

            g_bHostPlayer = g_pNetConnectWizard->IsHostPlayer();

            // Write information to the registry
            DXUtil_WriteStringRegKey( hDPlaySampleRegKey, TEXT("Player Name"), g_strLocalPlayerName );
            DXUtil_WriteStringRegKey( hDPlaySampleRegKey, TEXT("Session Name"), g_strSessionName );
            DXUtil_WriteStringRegKey( hDPlaySampleRegKey, TEXT("Preferred Provider"), g_strPreferredProvider );
        }
    }

    if( bConnectSuccess )
    {
        // Set default DirectPlayVoice setup options
        ZeroMemory( &g_dvClientConfig, sizeof(g_dvClientConfig) );
        g_dvClientConfig.dwSize                 = sizeof(g_dvClientConfig);
        g_dvClientConfig.dwFlags                = DVCLIENTCONFIG_AUTOVOICEACTIVATED |
                                                  DVCLIENTCONFIG_AUTORECORDVOLUME;
        g_dvClientConfig.lPlaybackVolume        = DVPLAYBACKVOLUME_DEFAULT;
        g_dvClientConfig.dwBufferQuality        = DVBUFFERQUALITY_DEFAULT;
        g_dvClientConfig.dwBufferAggressiveness = DVBUFFERAGGRESSIVENESS_DEFAULT;
        g_dvClientConfig.dwThreshold          = DVTHRESHOLD_UNUSED;
        g_dvClientConfig.lRecordVolume          = DVRECORDVOLUME_LAST;
        g_dvClientConfig.dwNotifyPeriod         = 0;

        g_guidDVSessionCT                       = DPVCTGUID_DEFAULT;

        // Ask the user for DirectPlayVoice setup params
        DWORD dwResult = (DWORD)DialogBox( hInst, MAKEINTRESOURCE(IDD_VOICE_SETUP), 
                                           NULL, (DLGPROC) VoiceConfigDlgProc );
        if( dwResult != IDCANCEL )
            g_pNetVoice->ChangeVoiceClientSettings( &g_dvClientConfig );
    }

    if( bConnectSuccess )
    {
        // App is now connected via DirectPlay, so start the game.  

        // For this sample, we just start a simple dialog box game.
        g_hrDialog = S_OK;
        DialogBox( hInst, MAKEINTRESOURCE(IDD_MAIN_GAME), NULL, (DLGPROC) VoiceDlgProc );

        if( FAILED( g_hrDialog ) )
        {
            if( g_hrDialog == DPNERR_CONNECTIONLOST )
            {
                MessageBox( NULL, TEXT("The DirectPlay session was lost. ")
                            TEXT("The sample will now quit."),
                            TEXT("DirectPlay Sample"), MB_OK | MB_ICONERROR );
            }
            else
            {
                DXTRACE_ERR_MSGBOX( TEXT("DialogBox"), hr );
                MessageBox( NULL, TEXT("An error occured during the game. ")
                            TEXT("The sample will now quit."),
                            TEXT("DirectPlay Sample"), MB_OK | MB_ICONERROR );
            }
        }
    }
    
    // Cleanup player ID array 
    free( g_pPlayers );

    // Disconnect from the DirectPlayVoice session, 
    // and destory it if we are the host player.
    SAFE_DELETE( g_pNetVoice ); 

    // Cleanup DirectPlay and helper classes
    g_pNetConnectWizard->Shutdown();

    if( g_pDP )
    {
        g_pDP->Close(0);
        SAFE_RELEASE( g_pDP );
    }

    if( g_pLobbiedApp )
    {
        g_pLobbiedApp->Close( 0 );
        SAFE_RELEASE( g_pLobbiedApp );
    }    

    // Don't delete the wizard until we know that 
    // DirectPlay is out of its message handlers.
    // This will be true after Close() has been called. 
    SAFE_DELETE( g_pNetConnectWizard );

    RegCloseKey( hDPlaySampleRegKey );
    DeleteCriticalSection( &g_csPlayerContext );
    CoUninitialize();

    return TRUE;
}




//-----------------------------------------------------------------------------
// Name: InitDirectPlay()
// Desc: 
//-----------------------------------------------------------------------------
HRESULT InitDirectPlay()
{
    DPNHANDLE hLobbyLaunchedConnection = NULL;
    HRESULT hr;

    // Create IDirectPlay8Peer
    if( FAILED( hr = CoCreateInstance( CLSID_DirectPlay8Peer, NULL, 
                                       CLSCTX_INPROC_SERVER,
                                       IID_IDirectPlay8Peer, 
                                       (LPVOID*) &g_pDP ) ) )
        return DXTRACE_ERR_MSGBOX( TEXT("CoCreateInstance"), hr );

    // Create IDirectPlay8LobbiedApplication
    if( FAILED( hr = CoCreateInstance( CLSID_DirectPlay8LobbiedApplication, NULL, 
                                       CLSCTX_INPROC_SERVER,
                                       IID_IDirectPlay8LobbiedApplication, 
                                       (LPVOID*) &g_pLobbiedApp ) ) )
        return DXTRACE_ERR_MSGBOX( TEXT("CoCreateInstance"), hr );

    // Init the helper class, now that g_pDP and g_pLobbiedApp are valid
    g_pNetConnectWizard->Init( g_pDP, g_pLobbiedApp );

    // Turn off parameter validation in release builds
#ifdef _DEBUG
    const DWORD dwInitFlags = 0;
#else
    const DWORD dwInitFlags = DPNINITIALIZE_DISABLEPARAMVAL;
#endif // _DEBUG

    // Init IDirectPlay8Peer
    if( FAILED( hr = g_pDP->Initialize( NULL, DirectPlayMessageHandler, dwInitFlags ) ) )
        return DXTRACE_ERR_MSGBOX( TEXT("Initialize"), hr );

    // Init IDirectPlay8LobbiedApplication.  Before this Initialize() returns 
    // a DPL_MSGID_CONNECT msg may come in to the DirectPlayLobbyMessageHandler 
    // so be prepared ahead of time.
    if( FAILED( hr = g_pLobbiedApp->Initialize( NULL, DirectPlayLobbyMessageHandler, 
                                                &hLobbyLaunchedConnection, dwInitFlags ) ) )
        return DXTRACE_ERR_MSGBOX( TEXT("Initialize"), hr );

    // IDirectPlay8LobbiedApplication::Initialize returns a handle to a connnection
    // if we have been lobby launced.  Initialize is guanteeded to return after 
    // the DPL_MSGID_CONNECT msg has been processed.  So unless a we are expected 
    // multiple lobby connections, we do not need to remember the lobby connection
    // handle since it will be recorded upon the DPL_MSGID_CONNECT msg.
    g_bWasLobbyLaunched = ( hLobbyLaunchedConnection != NULL );

    return S_OK;
}




//-----------------------------------------------------------------------------
// Name: VoiceDlgProc()
// Desc: Handles dialog messages
//-----------------------------------------------------------------------------
INT_PTR CALLBACK VoiceDlgProc( HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam )
{
    switch( msg ) 
    {
        case WM_INITDIALOG:
            {
                g_hDlg = hDlg;

                if( FAILED( g_hrDialog = g_pNetVoice->Init( hDlg, g_bHostPlayer, TRUE,
                                                            g_pDP, DVSESSIONTYPE_PEER, 
                                                            &g_guidDVSessionCT, &g_dvClientConfig ) ) )
                {
                    if( g_hrDialog == DVERR_USERBACK )
                    {
                        MessageBox( hDlg, TEXT("The user backed out of the wizard.  ")
                                    TEXT("This simple sample does not handle this case, so ")
                                    TEXT("the sample will quit."), TEXT("DirectPlay Sample"), MB_OK );
                        g_hrDialog = S_OK;
                    }

                    if( g_hrDialog == DVERR_USERCANCEL )
                    {
                        MessageBox( hDlg, TEXT("The user canceled the wizard. ")
                                    TEXT("This simple sample does not handle this case, so ")
                                    TEXT("the sample will quit."), TEXT("DirectPlay Sample"), MB_OK );
                        g_hrDialog = S_OK;
                    }

                    if( g_hrDialog == DVERR_ALREADYPENDING )
                    {
                        MessageBox( hDlg, TEXT("Another instance of the Voice Setup Wizard is already running. ")
                                    TEXT("This simple sample does not handle this case, so ")
                                    TEXT("the sample will quit."), TEXT("DirectPlay Sample"), MB_OK );
                        g_hrDialog = S_OK;
                    }

                    if( FAILED(g_hrDialog) )
                        DXTRACE_ERR_MSGBOX( TEXT("Init"), g_hrDialog );

                    EndDialog( hDlg, 0 );
                    break;
                }

                if( g_pNetVoice->IsHalfDuplex() ) 
                {
                    MessageBox( hDlg, TEXT("You are running in half duplex mode. In half duplex mode no recording takes place."), 
                                TEXT("DirectPlay Sample"), MB_OK );
                }

                g_bVoiceSessionInProgress = TRUE;

                if( FAILED( g_hrDialog = OnInitDialog( hDlg ) ) )
                {
                    DXTRACE_ERR_MSGBOX( TEXT("OnInitDialog"), g_hrDialog );
                    EndDialog( hDlg, 0 );
                    break;
                }
            }
            break;

        case WM_COMMAND:
            switch( LOWORD(wParam) )
            {
                case IDC_SETUP:
                    {
                        // Ask the user for DirectPlayVoice setup params
                        DWORD dwResult = (DWORD)DialogBox( g_hInst, 
                                                           MAKEINTRESOURCE(IDD_VOICE_SETUP), 
                                                           hDlg, (DLGPROC) VoiceConfigDlgProc );
                        if( dwResult != IDCANCEL )
                            g_pNetVoice->ChangeVoiceClientSettings( &g_dvClientConfig );
                    }
                    return TRUE;

                case IDC_CYCLEGROUP:
                    {
                        if( g_pPlayerLocal )
                        {
                            g_pPlayerLocal->ps.dwGroup++;
                            g_pPlayerLocal->ps.dwGroup %= MAX_GROUPS + 1;
                        }

                        if( FAILED( g_hrDialog = SetGroupAndTarget() ) )
                        {
                            DXTRACE_ERR_MSGBOX( TEXT("SetGroupAndTarget"), g_hrDialog );
                            EndDialog( hDlg, 0 );
                            break;
                        }

                        if( FAILED( g_hrDialog = SendLocalStateToAll( hDlg ) ) )
                        {
                            DXTRACE_ERR_MSGBOX( TEXT("SendLocalStateToAll"), g_hrDialog );
                            EndDialog( hDlg, 0 );
                            break;
                        }

                        // Update the listbox 
                        PostMessage( g_hDlg, WM_APP_DISPLAY_PLAYERS, 0, 0 );
                    }
                    break;

                case IDC_CYCLETARGET:
                    {
                        if( g_pPlayerLocal )
                        {
                            g_pPlayerLocal->ps.dwTarget++;
                            g_pPlayerLocal->ps.dwTarget %= MAX_GROUPS + 1;
                        }

                        if( FAILED( g_hrDialog = SetGroupAndTarget() ) )
                        {
                            DXTRACE_ERR_MSGBOX( TEXT("SetGroupAndTarget"), g_hrDialog );
                            EndDialog( hDlg, 0 );
                            break;
                        }

                        if( FAILED( g_hrDialog = SendLocalStateToAll( hDlg ) ) )
                        {
                            DXTRACE_ERR_MSGBOX( TEXT("SendLocalStateToAll"), g_hrDialog );
                            EndDialog( hDlg, 0 );
                            break;
                        }

                        // Update the listbox 
                        PostMessage( g_hDlg, WM_APP_DISPLAY_PLAYERS, 0, 0 );
                    }
                    break;

                case IDCANCEL:
                    g_hrDialog = S_OK;
                    EndDialog( hDlg, 0 );
                    return TRUE;
            }
            break;

        case WM_APP_DISPLAY_PLAYERS:
        {
            DisplayPlayersInChat( hDlg );
            RefreshStatusBarText( g_LocalPlayerDPNID, g_HostPlayerDPNID );
            break;
        }

        case WM_TIMER:
        {
            DWORD            dwNumPlayers;
            DWORD            iIndex;
            LVITEM           lvItem;
            HWND             hListView = GetDlgItem( hDlg, IDC_PEOPLE_LIST );

            dwNumPlayers = ListView_GetItemCount( hListView );

            // Now that they are added and the listview sorted them by name,
            // run through them all caching the listview index with its dpnid
            for( iIndex = 0; iIndex < dwNumPlayers; iIndex++ )
            {
                HRESULT hr;
                APP_PLAYER_INFO* pPlayerInfo = NULL;
                DPNID dpnidPlayer;

                lvItem.mask  = LVIF_PARAM;
                lvItem.iItem = iIndex;
                ListView_GetItem( hListView, &lvItem );

                dpnidPlayer = (DPNID) lvItem.lParam;

                PLAYER_LOCK(); // enter player context CS

                // Get the player context accosicated with this DPNID
                hr = g_pDP->GetPlayerContext( dpnidPlayer, 
                                              (LPVOID* const) &pPlayerInfo,
											  0);


                PLAYER_ADDREF( pPlayerInfo ); // addref player, since we are using it now
                PLAYER_UNLOCK(); // leave player context CS

                if( FAILED(hr) || pPlayerInfo == NULL )
                {
                    // The player who sent this may have gone away before this 
                    // message was handled, so just ignore it
                    continue;
                }

                TCHAR strStatus[255];

                if( pPlayerInfo->bHalfDuplex )
                {
                    _tcscpy( strStatus, TEXT("Can't talk") );
                }
                else
                {
                    if( pPlayerInfo->bTalking )
                        _tcscpy( strStatus, TEXT("Talking") );
                    else
                        _tcscpy( strStatus, TEXT("Silent") );
                }

                lvItem.iItem      = iIndex;
                lvItem.iSubItem   = 1;
                lvItem.mask       = LVIF_TEXT;
                lvItem.pszText    = strStatus;

                PLAYER_LOCK();
                PLAYER_RELEASE( pPlayerInfo );  // Release player and cleanup if needed
                PLAYER_UNLOCK();

                SendMessage( hListView, LVM_SETITEM, 0, (LPARAM) &lvItem );
            }
            break;
        }
    }

    return FALSE; // Didn't handle message
}




//-----------------------------------------------------------------------------
// Name: OnInitDialog()
// Desc: Inits the dialog 
//-----------------------------------------------------------------------------
HRESULT OnInitDialog( HWND hDlg )
{
    HRESULT  hr;
    LVCOLUMN column;
    RECT     rctListView;
    TCHAR    strHeader[255];
    DWORD    dwVertScrollBar;
    DWORD    dwListViewWidth;

    // Load and set the icon
    HICON hIcon = LoadIcon( g_hInst, MAKEINTRESOURCE( IDI_MAIN ) );
    SendMessage( hDlg, WM_SETICON, ICON_BIG,   (LPARAM) hIcon );  // Set big icon
    SendMessage( hDlg, WM_SETICON, ICON_SMALL, (LPARAM) hIcon );  // Set small icon

    if( g_bHostPlayer )
        SetWindowText( hDlg, TEXT("VoiceGroup (Session Host)") );
    else
        SetWindowText( hDlg, TEXT("VoiceGroup (Session Client)") );

    SetDlgItemText( hDlg, IDC_GROUP_TEXT, TEXT("Unassigned") );
    SetDlgItemText( hDlg, IDC_TARGET_TEXT, TEXT("Everyone") );

    // Setup the listview
    HWND hListView = GetDlgItem( hDlg, IDC_PEOPLE_LIST );

    dwVertScrollBar = GetSystemMetrics( SM_CXVSCROLL );  
    GetClientRect( hListView, &rctListView );
    dwListViewWidth = rctListView.right - dwVertScrollBar;
    column.mask     = LVCF_FMT | LVCF_SUBITEM | LVCF_TEXT | LVCF_WIDTH;
    column.fmt      = LVCFMT_LEFT;
    column.iSubItem = -1;

    // Insert the Name column
    _tcscpy( strHeader, TEXT("Name") );
    column.cx         = dwListViewWidth * 8 / 21;
    column.pszText    = strHeader;
    column.cchTextMax = (int) _tcslen( strHeader );
    ListView_InsertColumn( hListView, 0, &column );

    // Insert the Status column
    _tcscpy( strHeader, TEXT("Status") );
    column.cx         = dwListViewWidth * 4 / 21;
    column.pszText    = strHeader;
    column.cchTextMax = (int) _tcslen( strHeader );
    ListView_InsertColumn( hListView, 1, &column );

    // Insert the Group column
    _tcscpy( strHeader, TEXT("Group") );
    column.cx         = dwListViewWidth * 5 / 21;
    column.pszText    = strHeader;
    column.cchTextMax = (int) _tcslen( strHeader );
    ListView_InsertColumn( hListView, 2, &column );

    // Insert the Target column
    _tcscpy( strHeader, TEXT("Target") );
    column.cx         = dwListViewWidth * 4 / 21;
    column.pszText    = strHeader;
    column.cchTextMax = (int) _tcslen( strHeader );
    ListView_InsertColumn( hListView, 3, &column );

    if( FAILED( hr = SetGroupAndTarget() ) )
        return DXTRACE_ERR_MSGBOX( TEXT("SetGroupAndTarget"), hr );
    if( FAILED( hr = SendLocalStateToAll( hDlg ) ) )
        return DXTRACE_ERR_MSGBOX( TEXT("SendLocalStateToAll"), hr );

    // Update the listbox 
    PostMessage( g_hDlg, WM_APP_DISPLAY_PLAYERS, 0, 0 );

    // Make a timer to update the listbox 
    // 'Status' column every so often 
    SetTimer( hDlg, 0, 250, NULL );

    // Create the groups if we are the host player
    if( g_bHostPlayer )
    {
        DWORD dwIndex;

        for( dwIndex = 1; dwIndex < MAX_GROUPS + 1; dwIndex++ )
        {
            
            DWORD* pdwData = new DWORD;
            if( NULL == pdwData )
                return DXTRACE_ERR_MSGBOX( TEXT("OnInitDialog"), E_OUTOFMEMORY );

            *pdwData = dwIndex;

            DPN_GROUP_INFO dpGroupInfo;
            ZeroMemory( &dpGroupInfo, sizeof(DPN_GROUP_INFO) );
            dpGroupInfo.dwSize = sizeof( DPN_GROUP_INFO );
            dpGroupInfo.dwInfoFlags = DPNINFO_DATA;
            dpGroupInfo.pvData = pdwData;
            dpGroupInfo.dwDataSize = sizeof(DWORD);

            DPNHANDLE hAsync;
            hr = g_pDP->CreateGroup( &dpGroupInfo, NULL,
                                     NULL, &hAsync, 0 );
            if( FAILED( hr ) ) 
            {
                SAFE_DELETE( pdwData );
                return DXTRACE_ERR_MSGBOX( TEXT("CreateGroup"), hr );
            }
        }
    }

    return S_OK;
}




//-----------------------------------------------------------------------------
// Name: DisplayPlayersInChat()
// Desc: Displays the active players in the listview
//-----------------------------------------------------------------------------
HRESULT DisplayPlayersInChat( HWND hDlg )
{
    if( hDlg == NULL )
        return S_OK;

    HRESULT hr;
    LVITEM  lvItem;
    HWND    hListView = GetDlgItem( hDlg, IDC_PEOPLE_LIST );
    TCHAR   strText[32];
    TCHAR   strNumberPlayers[32];
    DWORD   dwNumPlayers;
    APP_PLAYER_INFO* pPlayerInfo = NULL;

    // Remove all the players and re-add them in the player enum callback
    ListView_DeleteAllItems( hListView );

    do
    {
        // Enum all players in the player ID array
        dwNumPlayers = g_dwPlayersArraySize;
        hr = g_pDP->EnumPlayersAndGroups( g_pPlayers, &dwNumPlayers, DPNENUM_PLAYERS );
        if( SUCCEEDED(hr) )
            break;

        if( hr == DPNERR_BUFFERTOOSMALL )
        {
            // Resize player pointer array     
            g_dwPlayersArraySize += 10;

            DPNID* pPlayersNew = (DPNID*) realloc( g_pPlayers, sizeof(DPNID)*g_dwPlayersArraySize );
            
            // Verify allocation
            if( NULL == pPlayersNew )
                hr = DXTRACE_ERR_MSGBOX( TEXT("DisplayPlayersInChat"), E_OUTOFMEMORY );
            else
                g_pPlayers = pPlayersNew;
        }
    } 
    while( hr == DPNERR_BUFFERTOOSMALL );
    if( FAILED(hr) )
        return DXTRACE_ERR_MSGBOX( TEXT("EnumPlayersAndGroups"), hr );

    for( DWORD i = 0; i<dwNumPlayers; i++ )
    {
        PLAYER_LOCK(); // enter player context CS

        do
        {
            // Get the player context accosicated with this DPNID
            // Call GetPlayerContext() until it returns something other than DPNERR_NOTREADY
            // DPNERR_NOTREADY will be returned if the callback thread has not 
            // yet returned from DPN_MSGID_CREATE_PLAYER, which sets the player's context
            hr = g_pDP->GetPlayerContext( g_pPlayers[i], 
                                          (LPVOID* const) &pPlayerInfo,
									      0);
        } 
        while( hr == DPNERR_NOTREADY ); 

        PLAYER_ADDREF( pPlayerInfo ); // addref player, since we are using it now
        PLAYER_UNLOCK(); // leave player context CS

        if( FAILED(hr) || pPlayerInfo == NULL )
        {
            // The player who sent this may have gone away before this 
            // message was handled, so just ignore it
            continue;
        }

        ZeroMemory( &lvItem, sizeof(lvItem) );

        // Add the item, saving the player's name and dpnid in the listview
        lvItem.mask       = LVIF_TEXT | LVIF_PARAM;
        lvItem.iItem      = 0;
        lvItem.iSubItem   = 0;
        lvItem.pszText    = pPlayerInfo->strPlayerName;
        lvItem.lParam     = g_pPlayers[i];
        lvItem.cchTextMax = (int) _tcslen( pPlayerInfo->strPlayerName );
        int nIndex = ListView_InsertItem( hListView, &lvItem );

        if( pPlayerInfo->bHalfDuplex )
        {
            _tcscpy( strText, TEXT("Can't talk") );
        }
        else
        {
            if( pPlayerInfo->bTalking )
                _tcscpy( strText, TEXT("Talking") );
            else
                _tcscpy( strText, TEXT("Silent") );
        }

        // Start the player's status off as silent.  
        lvItem.mask       = LVIF_TEXT;
        lvItem.iItem      = nIndex;
        lvItem.iSubItem   = 1;
        lvItem.pszText    = strText;
        lvItem.cchTextMax = (int) _tcslen( strText );
        ListView_SetItem( hListView, &lvItem );

        if( pPlayerInfo->ps.dwGroup == 0 )
            _tcscpy( strText, TEXT("Unassigned") );
        else
            wsprintf( strText, TEXT("%d"), pPlayerInfo->ps.dwGroup );

        lvItem.mask       = LVIF_TEXT;
        lvItem.iItem      = nIndex;
        lvItem.iSubItem   = 2;
        lvItem.pszText    = strText;
        lvItem.cchTextMax = (int) _tcslen( strText );
        ListView_SetItem( hListView, &lvItem );

        if( pPlayerInfo->ps.dwTarget == 0 )
            _tcscpy( strText, TEXT("Everyone") );
        else
            wsprintf( strText, TEXT("%d"), pPlayerInfo->ps.dwTarget );

        PLAYER_LOCK();
        PLAYER_RELEASE( pPlayerInfo );  // Release player and cleanup if needed
        PLAYER_UNLOCK();

        lvItem.mask       = LVIF_TEXT;
        lvItem.iItem      = nIndex;
        lvItem.iSubItem   = 3;
        lvItem.pszText    = strText;
        lvItem.cchTextMax = (int) _tcslen( strText );
        ListView_SetItem( hListView, &lvItem );
    }

    wsprintf( strNumberPlayers, TEXT("%d"), dwNumPlayers );
    SetDlgItemText( hDlg, IDC_NUM_PLAYERS, strNumberPlayers );

    if( g_pPlayerLocal )
    {
        if( g_pPlayerLocal->ps.dwGroup == 0 )
            _tcscpy( strText, TEXT("Unassigned") );
        else
            wsprintf( strText, TEXT("Group #%d"), g_pPlayerLocal->ps.dwGroup );
        SetDlgItemText( hDlg, IDC_GROUP_TEXT, strText );

        if( g_pPlayerLocal->ps.dwTarget == 0 )
            _tcscpy( strText, TEXT("Everyone") );
        else
            wsprintf( strText, TEXT("Group #%d"), g_pPlayerLocal->ps.dwTarget );
        SetDlgItemText( hDlg, IDC_TARGET_TEXT, strText );
    }


    return S_OK;
}




//-----------------------------------------------------------------------------
// Name: SendLocalStateToAll()
// Desc: Send the local player's state to all of the players
//-----------------------------------------------------------------------------
HRESULT SendLocalStateToAll( HWND hDlg )
{
    if( g_pPlayerLocal )
    {
        GAMEMSG_PLAYERSTATECHANGE msgPlayerStateChange;
        msgPlayerStateChange.dwType = GAME_MSGID_PLAYERSTATECHANGE;
        msgPlayerStateChange.ps     = g_pPlayerLocal->ps; 

        DPN_BUFFER_DESC bufferDesc;
        bufferDesc.dwBufferSize = sizeof(GAMEMSG_PLAYERSTATECHANGE);
        bufferDesc.pBufferData  = (BYTE*) &msgPlayerStateChange;

        // DirectPlay will tell via the message handler 
        // if there are any severe errors, so ignore any errors 
        DPNHANDLE hAsync;
        g_pDP->SendTo( DPNID_ALL_PLAYERS_GROUP, &bufferDesc, 1,
                       0, NULL, &hAsync, DPNSEND_NOLOOPBACK | DPNSEND_GUARANTEED );
    }

    return S_OK;
}




//-----------------------------------------------------------------------------
// Name: SetGroupAndTarget()
// Desc: 
//-----------------------------------------------------------------------------
HRESULT SetGroupAndTarget()
{
    HRESULT hr;
    DPNID* aGroupsDPNID = NULL;
    DPN_GROUP_INFO* pdpGroupInfo = NULL;
    DWORD dwCount = 0;

    LPDIRECTPLAYVOICECLIENT pVoiceClient = g_pNetVoice->GetVoiceClient();
    if( pVoiceClient && g_pPlayerLocal->ps.dwTarget == 0 )
    {
        // Talk to everyone in the session 
        DVID dvid = DVID_ALLPLAYERS;
        if( FAILED( hr = pVoiceClient->SetTransmitTargets( &dvid, 1, 0 ) ) )
        {
            DXTRACE_ERR_MSGBOX( TEXT("SetTransmitTargets"), hr );
            goto LCleanReturn;
        }
    }

    if( g_LocalGroupDPNID != 0 )
    {
        // Remove player from current group
        DPNHANDLE hAsync;
        hr = g_pDP->RemovePlayerFromGroup( g_LocalGroupDPNID, 
                                           g_LocalPlayerDPNID,
                                           NULL, &hAsync, 0 );
        if( FAILED(hr) )
        {
            DXTRACE_ERR_MSGBOX( TEXT("RemovePlayerFromGroup"), hr );
            goto LCleanReturn;
        }

        g_LocalGroupDPNID = 0;
    }

    // Enumerate all groups to figure out which group we are target, and joining
    // A loop is needed here because a player could join between the call requesting
    // the size needed for the buffer and the call which performs the enumeration.
    for( ; ; )
    {
        hr = g_pDP->EnumPlayersAndGroups( aGroupsDPNID, &dwCount, DPNENUM_GROUPS );
        if( SUCCEEDED(hr) )
            break;

        SAFE_DELETE_ARRAY( aGroupsDPNID );

        if( FAILED(hr) && hr != DPNERR_BUFFERTOOSMALL )
        {
            DXTRACE_ERR_MSGBOX( TEXT("EnumPlayersAndGroups"), hr );
            goto LCleanReturn;
        }

        aGroupsDPNID = new DPNID[ dwCount ];
        if( NULL == aGroupsDPNID )
        {
            DXTRACE_ERR_MSGBOX( TEXT("SetGroupAndTarget"), E_OUTOFMEMORY );
            goto LCleanReturn;
        }
    }
   
    DWORD i;
    for( i=0; i<dwCount; i++ )
    {
        DWORD dwGroupNumber;

        // Get group info 
        DWORD dwSize = 0;
    
        hr = g_pDP->GetGroupInfo( aGroupsDPNID[i], pdpGroupInfo, &dwSize, 0 );
        if( FAILED(hr) && hr != DPNERR_BUFFERTOOSMALL )
        {
            DXTRACE_ERR_MSGBOX( TEXT("GetGroupInfo"), hr );
            goto LCleanReturn;
        }

        pdpGroupInfo = (DPN_GROUP_INFO*) new BYTE[ dwSize ];
        if( NULL == pdpGroupInfo )
        {
            hr = E_OUTOFMEMORY;
            DXTRACE_ERR_MSGBOX( TEXT("SetGroupAndTarget"), hr );
            goto LCleanReturn;
        }

        ZeroMemory( pdpGroupInfo, dwSize );
        pdpGroupInfo->dwSize = sizeof(DPN_GROUP_INFO); 
        hr = g_pDP->GetGroupInfo( aGroupsDPNID[i], pdpGroupInfo, &dwSize, 0 );
        if( FAILED(hr) )
        {
            DXTRACE_ERR_MSGBOX( TEXT("GetGroupInfo"), hr );
            goto LCleanReturn;
        }

        if( pdpGroupInfo->pvData )
            dwGroupNumber = *( (DWORD*) pdpGroupInfo->pvData );
        else
            dwGroupNumber = 0;

        SAFE_DELETE_ARRAY( pdpGroupInfo );

        if( dwGroupNumber == 0 )
            continue;

        if( dwGroupNumber == g_pPlayerLocal->ps.dwGroup )
        {
            g_LocalGroupDPNID = aGroupsDPNID[i];

            // Add player to this group
            DPNHANDLE hAsync;
            hr = g_pDP->AddPlayerToGroup( aGroupsDPNID[i], g_LocalPlayerDPNID, 
                                                      NULL, &hAsync, 0 );
            if( FAILED( hr ) ) 
            {
                DXTRACE_ERR_MSGBOX( TEXT("AddPlayerToGroup"), hr );
                goto LCleanReturn;
            }
        }

        if( dwGroupNumber == g_pPlayerLocal->ps.dwTarget )
        {
            // Talk to just this group
            hr = pVoiceClient->SetTransmitTargets( &aGroupsDPNID[i], 1, 0 );
            if( FAILED( hr ) ) 
            {
                DXTRACE_ERR_MSGBOX( TEXT("SetTransmitTargets"), hr );
                goto LCleanReturn;
            }
        }
    }

    hr = S_OK;

LCleanReturn:
    SAFE_DELETE_ARRAY( aGroupsDPNID );
    SAFE_DELETE_ARRAY( pdpGroupInfo );

    return hr;
}




//-----------------------------------------------------------------------------
// Name: DirectPlayMessageHandler
// Desc: Handler for DirectPlay messages.  This function is called by
//       the DirectPlay message handler pool of threads, so be care of thread
//       synchronization problems with shared memory
//-----------------------------------------------------------------------------
HRESULT WINAPI DirectPlayMessageHandler( PVOID pvUserContext, 
                                         DWORD dwMessageId, 
                                         PVOID pMsgBuffer )
{
    // Try not to stay in this message handler for too long, otherwise
    // there will be a backlog of data.  The best solution is to 
    // queue data as it comes in, and then handle it on other threads.
    
    // This function is called by the DirectPlay message handler pool of 
    // threads, so be care of thread synchronization problems with shared memory

    switch( dwMessageId )
    {
        case DPN_MSGID_CREATE_PLAYER:
        {
            HRESULT hr;
            PDPNMSG_CREATE_PLAYER pCreatePlayerMsg;
            pCreatePlayerMsg = (PDPNMSG_CREATE_PLAYER) pMsgBuffer;

            // Create a new and fill in a APP_PLAYER_INFO
            APP_PLAYER_INFO* pPlayerInfo = new APP_PLAYER_INFO;
            if( NULL == pPlayerInfo )
                break;

            ZeroMemory( pPlayerInfo, sizeof(APP_PLAYER_INFO) );
            pPlayerInfo->dpnidPlayer = pCreatePlayerMsg->dpnidPlayer;
            pPlayerInfo->lRefCount   = 1;

            // Get the peer info and extract its name
            DWORD dwSize = 0;
            DPN_PLAYER_INFO* pdpPlayerInfo = NULL;
            hr = DPNERR_CONNECTING;
            
            // GetPeerInfo might return DPNERR_CONNECTING when connecting, 
            // so just keep calling it if it does
            while( hr == DPNERR_CONNECTING ) 
                hr = g_pDP->GetPeerInfo( pCreatePlayerMsg->dpnidPlayer, pdpPlayerInfo, &dwSize, 0 );                                
                
            if( hr == DPNERR_BUFFERTOOSMALL )
            {
                pdpPlayerInfo = (DPN_PLAYER_INFO*) new BYTE[ dwSize ];
                ZeroMemory( pdpPlayerInfo, dwSize );
                pdpPlayerInfo->dwSize = sizeof(DPN_PLAYER_INFO);
                
                hr = g_pDP->GetPeerInfo( pCreatePlayerMsg->dpnidPlayer, pdpPlayerInfo, &dwSize, 0 );
                if( SUCCEEDED(hr) )
                {
                    // This stores a extra TCHAR copy of the player name for 
                    // easier access.  This will be redundent copy since DPlay 
                    // also keeps a copy of the player name in GetPeerInfo()
                    DXUtil_ConvertWideStringToGenericCch( pPlayerInfo->strPlayerName, 
                                                          pdpPlayerInfo->pwszName, MAX_PLAYER_NAME );    
                                                       
                    // See if this is the local player
                    if( (pdpPlayerInfo->dwPlayerFlags & DPNPLAYER_LOCAL) != 0 )
                    {
                        g_pPlayerLocal = pPlayerInfo;
                        g_pPlayerLocal->ps.dwGroup  = 0;
                        g_pPlayerLocal->ps.dwTarget = 0;
                        g_LocalPlayerDPNID = pCreatePlayerMsg->dpnidPlayer;
                    }     
                    if( (pdpPlayerInfo->dwPlayerFlags & DPNPLAYER_HOST) != 0 )
                        g_HostPlayerDPNID = pCreatePlayerMsg->dpnidPlayer;
                }

                SAFE_DELETE_ARRAY( pdpPlayerInfo );
            }

            // Tell DirectPlay to store this pPlayerInfo 
            // pointer in the pvPlayerContext.
            pCreatePlayerMsg->pvPlayerContext = pPlayerInfo;

            if( FAILED( hr = SendLocalStateToAll( g_hDlg ) ) )
                return DXTRACE_ERR_MSGBOX( TEXT("SendLocalStateToAll"), hr );

            // Post a message to the dialog thread to update the 
            // UI.  This keeps the DirectPlay message handler 
            // from blocking
            if( g_hDlg != NULL )
                PostMessage( g_hDlg, WM_APP_DISPLAY_PLAYERS, 0, 0 );
            break;
        }

        case DPN_MSGID_DESTROY_PLAYER:
        {
            PDPNMSG_DESTROY_PLAYER pDestroyPlayerMsg;
            pDestroyPlayerMsg = (PDPNMSG_DESTROY_PLAYER)pMsgBuffer;

            APP_PLAYER_INFO* pPlayerInfo = (APP_PLAYER_INFO*) pDestroyPlayerMsg->pvPlayerContext;
            
            PLAYER_LOCK();                  // enter player context CS
            PLAYER_RELEASE( pPlayerInfo );  // Release player and cleanup if needed
            PLAYER_UNLOCK();                // leave player context CS

            // Post a message to the dialog thread to update the 
            // UI.  This keeps the DirectPlay message handler 
            // from blocking
            if( g_hDlg != NULL )
                PostMessage( g_hDlg, WM_APP_DISPLAY_PLAYERS, 0, 0 );

            break;
        }

        case DPN_MSGID_HOST_MIGRATE:
        {
            PDPNMSG_HOST_MIGRATE pHostMigrateMsg;
            pHostMigrateMsg = (PDPNMSG_HOST_MIGRATE)pMsgBuffer;

            if( pHostMigrateMsg->dpnidNewHost == g_LocalPlayerDPNID )
            {
                SetWindowText( g_hDlg, TEXT("VoiceGroup (Session Host)") );
                g_bHostPlayer = TRUE;
            }

            g_HostPlayerDPNID = pHostMigrateMsg->dpnidNewHost;
            if( g_hDlg != NULL )
                PostMessage( g_hDlg, WM_APP_DISPLAY_PLAYERS, 0, 0 );

            break;
        }

        case DPN_MSGID_RECEIVE:
        {
            PDPNMSG_RECEIVE pReceiveMsg;
            pReceiveMsg = (PDPNMSG_RECEIVE)pMsgBuffer;

            // Validate incoming data: A malicious user could modify or create an application
            // to send bogus information; to help guard against logical errors and denial 
            // of service attacks, the size of incoming data should be checked against what
            // is expected.
            if( pReceiveMsg->dwReceiveDataSize < sizeof(GAMEMSG_GENERIC) )
                break;

            GAMEMSG_GENERIC* pMsg = (GAMEMSG_GENERIC*) pReceiveMsg->pReceiveData;
            if( pMsg->dwType == GAME_MSGID_PLAYERSTATECHANGE )
            {
                // Validate incoming data
                if( pReceiveMsg->dwReceiveDataSize != sizeof(GAMEMSG_PLAYERSTATECHANGE) )
                    break;

                GAMEMSG_PLAYERSTATECHANGE* pPlayerStateChangedMsg;
                pPlayerStateChangedMsg = (GAMEMSG_PLAYERSTATECHANGE*) pMsg;

                PLAYER_LOCK(); // enter player context CS

                APP_PLAYER_INFO* pPlayerInfo = (APP_PLAYER_INFO*) pReceiveMsg->pvPlayerContext;

                PLAYER_ADDREF( pPlayerInfo ); // addref player, since we are using it now
                PLAYER_UNLOCK(); // leave player context CS

                if( pPlayerInfo )
                    pPlayerInfo->ps = pPlayerStateChangedMsg->ps;

                PLAYER_LOCK();
                PLAYER_RELEASE( pPlayerInfo );  // Release player and cleanup if needed
                PLAYER_UNLOCK();

                // Post a message to the dialog thread to update the 
                // UI.  This keeps the DirectPlay message handler 
                // from blocking
                if( g_hDlg != NULL )
                    PostMessage( g_hDlg, WM_APP_DISPLAY_PLAYERS, 0, 0 );
            }
            break;
        }

        case DPN_MSGID_TERMINATE_SESSION:
        {
            PDPNMSG_TERMINATE_SESSION pTerminateSessionMsg;
            pTerminateSessionMsg = (PDPNMSG_TERMINATE_SESSION)pMsgBuffer;

            g_hrDialog = DPNERR_CONNECTIONLOST;
            EndDialog( g_hDlg, 0 );
            break;
        }
    }

    // Make sure the DirectPlay MessageHandler calls the CNetConnectWizard handler, 
    // so it can be informed of messages such as DPN_MSGID_ENUM_HOSTS_RESPONSE.
    if( g_pNetConnectWizard )
        return g_pNetConnectWizard->MessageHandler( pvUserContext, dwMessageId, pMsgBuffer );
    
    return S_OK;
}




//-----------------------------------------------------------------------------
// Name: DirectPlayLobbyMessageHandler
// Desc: Handler for DirectPlay lobby messages.  This function is called by
//       the DirectPlay lobby message handler pool of threads, so be careful of 
//       thread synchronization problems with shared memory
//-----------------------------------------------------------------------------
HRESULT WINAPI DirectPlayLobbyMessageHandler( PVOID pvUserContext, 
                                              DWORD dwMessageId, 
                                              PVOID pMsgBuffer )
{
    switch( dwMessageId )
    {
        case DPL_MSGID_CONNECT:
        {
            PDPL_MESSAGE_CONNECT pConnectMsg;
            pConnectMsg = (PDPL_MESSAGE_CONNECT)pMsgBuffer;

            // The CNetConnectWizard will handle this message for us,
            // so there is nothing we need to do here for this simple
            // sample.
            break;
        }

        case DPL_MSGID_DISCONNECT:
        {
            PDPL_MESSAGE_DISCONNECT pDisconnectMsg;
            pDisconnectMsg = (PDPL_MESSAGE_DISCONNECT)pMsgBuffer;

            // We should free any data associated with the lobby 
            // client here, but there is none.
            break;
        }

        case DPL_MSGID_RECEIVE:
        {
            PDPL_MESSAGE_RECEIVE pReceiveMsg;
            pReceiveMsg = (PDPL_MESSAGE_RECEIVE)pMsgBuffer;

            // The lobby client sent us data.  This sample doesn't
            // expected data from the client, but it is useful 
            // for more complex apps.
            break;
        }

        case DPL_MSGID_CONNECTION_SETTINGS:
        {
            PDPL_MESSAGE_CONNECTION_SETTINGS pConnectionStatusMsg;
            pConnectionStatusMsg = (PDPL_MESSAGE_CONNECTION_SETTINGS)pMsgBuffer;

            // The lobby client has changed the connection settings.  
            // This simple sample doesn't handle this, but more complex apps may
            // want to.
            break;
        }
    }

    // Make sure the DirectPlay MessageHandler calls the CNetConnectWizard handler, 
    // so the wizard can be informed of lobby messages such as DPL_MSGID_CONNECT
    if( g_pNetConnectWizard )
        return g_pNetConnectWizard->LobbyMessageHandler( pvUserContext, dwMessageId, 
                                                         pMsgBuffer );
    
    return S_OK;
}




//-----------------------------------------------------------------------------
// Name: DirectPlayVoiceServerMessageHandler()
// Desc: The callback for DirectPlayVoice server messages.  
//-----------------------------------------------------------------------------
HRESULT CALLBACK DirectPlayVoiceServerMessageHandler( LPVOID lpvUserContext, DWORD dwMessageType,
                                                      LPVOID lpMessage )
{
    // This simple sample doesn't respond to any server messages
    return S_OK;
}




//-----------------------------------------------------------------------------
// Name: DirectPlayVoiceClientMessageHandler()
// Desc: The callback for DirectPlayVoice client messages.  
//       This handles client messages and updates the UI the whenever a client 
//       starts or stops talking.  
//-----------------------------------------------------------------------------
HRESULT CALLBACK DirectPlayVoiceClientMessageHandler( LPVOID lpvUserContext, DWORD dwMessageType,
                                                      LPVOID lpMessage )
{
    // Try not to stay in this message handler for too long, otherwise
    // there will be a backlog of data.  The best solution is to 
    // queue data as it comes in, and then handle it on other threads.
    
    // This function is called by the DirectPlay message handler pool of 
    // threads, so be care of thread synchronization problems with shared memory
    HRESULT hr;
    HWND hDlg = (HWND) lpvUserContext;
 
    switch( dwMessageType )
    {
        case DVMSGID_CREATEVOICEPLAYER:
            {
                DVMSG_CREATEVOICEPLAYER* pCreateVoicePlayerMsg = (DVMSG_CREATEVOICEPLAYER*) lpMessage;
                APP_PLAYER_INFO* pPlayerInfo = NULL;

                PLAYER_LOCK(); // enter player context CS

                // Get the player context accosicated with this DPNID
                hr = g_pDP->GetPlayerContext( pCreateVoicePlayerMsg->dvidPlayer, 
                                              (LPVOID* const) &pPlayerInfo,
											  0);

                if( FAILED(hr) || pPlayerInfo == NULL )
                {
                    // The player who sent this may have gone away before this 
                    // message was handled, so just ignore it
                    PLAYER_UNLOCK();
                    break;
                }

                PLAYER_ADDREF( pPlayerInfo ); // addref player, for voice context value
                PLAYER_UNLOCK(); // leave player context CS

                pPlayerInfo->bHalfDuplex = ((pCreateVoicePlayerMsg->dwFlags & DVPLAYERCAPS_HALFDUPLEX) != 0);

                // Set voice context value
				pCreateVoicePlayerMsg->pvPlayerContext = pPlayerInfo;                

                // Post a message to the dialog thread to update the 
                // UI.  This keeps the DirectPlay message handler 
                // from blocking
                if( g_hDlg != NULL )
                    PostMessage( g_hDlg, WM_APP_DISPLAY_PLAYERS, 0, 0 );
            }
            break;

        case DVMSGID_DELETEVOICEPLAYER:
        {
            DVMSG_DELETEVOICEPLAYER* pMsg = (DVMSG_DELETEVOICEPLAYER*) lpMessage;
            APP_PLAYER_INFO* pPlayerInfo = (APP_PLAYER_INFO*) pMsg->pvPlayerContext;

            // Don't update the dlg if this message is for the local 
            // client since the dlg will be gone.
            if( pMsg->dvidPlayer != g_LocalPlayerDPNID )
            {
                // Post a message to the dialog thread to update the 
                // UI.  This keeps the DirectPlay message handler 
                // from blocking
                if( hDlg != NULL )
                    PostMessage( hDlg, WM_APP_DISPLAY_PLAYERS, 0, 0 );
			}

			// Release our extra reference on the player info that we have for the voice
			// context value.  
			//
            PLAYER_LOCK();
            PLAYER_RELEASE( pPlayerInfo );  
            PLAYER_UNLOCK();
            break;
        } 

        case DVMSGID_SESSIONLOST:
            g_hrDialog = DPNERR_CONNECTIONLOST;
            EndDialog( g_hDlg, 0 );
            break;

        case DVMSGID_HOSTMIGRATED:
        {
            DVMSG_HOSTMIGRATED* pMsg = (DVMSG_HOSTMIGRATED*) lpMessage;

            if( pMsg->pdvServerInterface != NULL )
            {           
                // If we keep the pMsg->pdvServerInterface pointer around, then
                // we must AddRef() it.  The CNetVoice::HostMigrate() automatically
                // does this for us.
                g_pNetVoice->HostMigrate( pMsg->pdvServerInterface );
            }
            break;
        }

        case DVMSGID_GAINFOCUS:
        case DVMSGID_LOSTFOCUS:
        {
            TCHAR strWindowName[MAX_PATH];
            wsprintf( strWindowName, TEXT("%s%s%s"), g_strAppName,
                (g_bHostPlayer)                      ? TEXT(" (Session Host)") : TEXT(""),
                (dwMessageType == DVMSGID_LOSTFOCUS) ? TEXT(" (Focus Lost)") : TEXT("") );

            SetWindowText( hDlg, strWindowName );
            break;
        }

        case DVMSGID_RECORDSTART:             
		{ 
			DVMSG_RECORDSTART* pMsg = (DVMSG_RECORDSTART*) lpMessage;
			SetPlayerTalking( (APP_PLAYER_INFO*) pMsg->pvLocalPlayerContext, TRUE );
            break;
        }
        case DVMSGID_RECORDSTOP:             
        {
			DVMSG_RECORDSTOP* pMsg = (DVMSG_RECORDSTOP*) lpMessage;
			SetPlayerTalking( (APP_PLAYER_INFO*) pMsg->pvLocalPlayerContext, FALSE );
            break;
        }
        case DVMSGID_PLAYERVOICESTART:
        {
            DVMSG_PLAYERVOICESTART* pMsg = (DVMSG_PLAYERVOICESTART*) lpMessage;
            SetPlayerTalking( (APP_PLAYER_INFO*) pMsg->pvPlayerContext, TRUE );
            break;
        }

        case DVMSGID_PLAYERVOICESTOP:
        {
            DVMSG_PLAYERVOICESTOP* pMsg = (DVMSG_PLAYERVOICESTOP*) lpMessage;
            SetPlayerTalking( (APP_PLAYER_INFO*) pMsg->pvPlayerContext, FALSE );        	
            break;
        }
        
    }

    return S_OK;
}




//-----------------------------------------------------------------------------
// Name: SetPlayerTalking()
// Desc: Set player talking flag
//-----------------------------------------------------------------------------
void SetPlayerTalking( APP_PLAYER_INFO* pPlayerInfo, BOOL bTalking )
{
    if( pPlayerInfo )
        pPlayerInfo->bTalking = bTalking; 	
}




//-----------------------------------------------------------------------------
// Name: VoiceConfigDlgProc()
// Desc: Prompt the user for DirectPlayVoice setup options
//-----------------------------------------------------------------------------
INT_PTR CALLBACK VoiceConfigDlgProc( HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam )
{
    DWORD dwSliderPos;

    switch( msg ) 
    {
        case WM_INITDIALOG:
            // Set the range on the sliders
            SendDlgItemMessage( hDlg, IDC_PLAYBACK_SLIDER,       TBM_SETRANGE, FALSE, MAKELONG( 0, 99 ) );
            SendDlgItemMessage( hDlg, IDC_RECORD_SLIDER,         TBM_SETRANGE, FALSE, MAKELONG( 0, 99 ) );
            SendDlgItemMessage( hDlg, IDC_THRESHOLD_SLIDER,    TBM_SETRANGE, FALSE, MAKELONG( DVTHRESHOLD_MIN,  DVTHRESHOLD_MAX ) );
            
            // Setup the dialog based on the globals 

            // Set the playback controls
            if( g_dvClientConfig.lPlaybackVolume == DVPLAYBACKVOLUME_DEFAULT )
            {
                CheckRadioButton( hDlg, IDC_PLAYBACK_DEFAULT, IDC_PLAYBACK_SET, IDC_PLAYBACK_DEFAULT );
            }
            else
            {
                dwSliderPos = (DWORD) ( ( g_dvClientConfig.lPlaybackVolume - DSBVOLUME_MIN ) * 
                                          100.0f / (DSBVOLUME_MAX-DSBVOLUME_MIN) );
                CheckRadioButton( hDlg, IDC_PLAYBACK_DEFAULT, IDC_PLAYBACK_SET, IDC_PLAYBACK_SET );
                SendDlgItemMessage( hDlg, IDC_PLAYBACK_SLIDER, TBM_SETPOS, TRUE, dwSliderPos );
            }

            // Set the record controls
            if( g_dvClientConfig.dwFlags & DVCLIENTCONFIG_AUTORECORDVOLUME )
            {
                CheckRadioButton( hDlg, IDC_RECORD_DEFAULT, IDC_RECORD_AUTO, IDC_RECORD_AUTO );
            }
            else if( g_dvClientConfig.lRecordVolume == DVPLAYBACKVOLUME_DEFAULT )
            {
                CheckRadioButton( hDlg, IDC_RECORD_DEFAULT, IDC_RECORD_AUTO, IDC_RECORD_DEFAULT );
            }
            else
            {
                dwSliderPos = (DWORD) ( ( g_dvClientConfig.lRecordVolume - DSBVOLUME_MIN ) * 
                                          100.0f / (DSBVOLUME_MAX-DSBVOLUME_MIN) );
                CheckRadioButton( hDlg, IDC_RECORD_DEFAULT, IDC_RECORD_AUTO, IDC_RECORD_SET );
                SendDlgItemMessage( hDlg, IDC_RECORD_SLIDER, TBM_SETPOS, TRUE, dwSliderPos );
            }

            // Set the threshold controls
            if( g_dvClientConfig.dwFlags & DVCLIENTCONFIG_AUTOVOICEACTIVATED )
            {
                CheckRadioButton( hDlg, IDC_THRESHOLD_DEFAULT, IDC_THRESHOLD_AUTO, IDC_THRESHOLD_AUTO );
            }
            else if( g_dvClientConfig.dwThreshold == DVTHRESHOLD_DEFAULT )
            {
                CheckRadioButton( hDlg, IDC_THRESHOLD_DEFAULT, IDC_THRESHOLD_AUTO, IDC_THRESHOLD_DEFAULT );
            }
            else
            {
                CheckRadioButton( hDlg, IDC_THRESHOLD_DEFAULT, IDC_THRESHOLD_AUTO, IDC_THRESHOLD_SET );
                SendDlgItemMessage( hDlg, IDC_THRESHOLD_SLIDER, TBM_SETPOS, TRUE, g_dvClientConfig.dwThreshold );
            }

            if( !g_bHostPlayer || g_bVoiceSessionInProgress )
            {
                // We are are not the host player then disable all the server only options 
                EnableWindow( GetDlgItem( hDlg, IDC_COMPRESSION_COMBO ), FALSE );
                EnableWindow( GetDlgItem( hDlg, IDC_SESSIONCOMPRESION_GROUP ), FALSE );
            }
            else
            {
                VoiceConfigEnumCompressionCodecs( hDlg );   
                EnableWindow( GetDlgItem( hDlg, IDCANCEL ), FALSE );
            }

            return TRUE;

        case WM_NOTIFY:
            #ifndef NM_RELEASEDCAPTURE
                #define NM_RELEASEDCAPTURE (NM_FIRST-16)
            #endif
            if( ((LPNMHDR) lParam)->code == NM_RELEASEDCAPTURE )
            {
                // If this is a release capture from a slider, then automatically check 
                // its 'Set' radio button.
                switch( ((LPNMHDR) lParam)->idFrom )
                {
                case IDC_PLAYBACK_SLIDER:
                    CheckRadioButton( hDlg, IDC_PLAYBACK_DEFAULT, IDC_PLAYBACK_SET, IDC_PLAYBACK_SET );
                    break;
    
                case IDC_RECORD_SLIDER:
                    CheckRadioButton( hDlg, IDC_RECORD_DEFAULT, IDC_RECORD_AUTO, IDC_RECORD_SET );
                    break;
    
                case IDC_THRESHOLD_SLIDER:
                    CheckRadioButton( hDlg, IDC_THRESHOLD_DEFAULT, IDC_THRESHOLD_AUTO, IDC_THRESHOLD_SET );
                    break;
                }
            }
            return TRUE;            

        case WM_COMMAND:
            switch( LOWORD(wParam) )
            {
                case IDOK:
                    VoiceConfigDlgOnOK( hDlg );
                    return TRUE;

                case IDCANCEL:
                    EndDialog( hDlg, IDCANCEL );
                    return TRUE;
            }
            break;
 
        case WM_DESTROY:
        {
            GUID* pGuid;
            int nCount = (int)SendDlgItemMessage( hDlg, IDC_COMPRESSION_COMBO, CB_GETCOUNT, 0, 0 );
            for( int i=0; i<nCount; i++ )
            {
                pGuid = (LPGUID) SendDlgItemMessage( hDlg, IDC_COMPRESSION_COMBO, CB_GETITEMDATA, i, 0 );
                SAFE_DELETE( pGuid );
            }
            break;
        }
   }

    return FALSE; // Didn't handle message
}




//-----------------------------------------------------------------------------
// Name: VoiceConfigEnumCompressionCodecs()
// Desc: Asks DirectPlayVoice what voice compression codecs are availible
//       and fills the combo box thier names and GUIDs.
//-----------------------------------------------------------------------------
HRESULT VoiceConfigEnumCompressionCodecs( HWND hDlg )
{
    LPDIRECTPLAYVOICECLIENT pVoiceClient        = NULL;
    LPDVCOMPRESSIONINFO     pdvCompressionInfo  = NULL;
    LPGUID  pGuid         = NULL;
    LPBYTE  pBuffer       = NULL;
    DWORD   dwSize        = 0;
    DWORD   dwNumElements = 0;
    HWND    hPulldown     = GetDlgItem( hDlg, IDC_COMPRESSION_COMBO );
    HRESULT hr;
    LONG    lIndex;
    LONG    lFirst        = -1;

    if( FAILED( hr = CoCreateInstance( CLSID_DirectPlayVoiceClient, NULL, 
                                       CLSCTX_INPROC_SERVER, IID_IDirectPlayVoiceClient, 
                                       (VOID**) &pVoiceClient ) ) )
        return DXTRACE_ERR_MSGBOX( TEXT("CoCreateInstance"), hr ); 
        

    hr = pVoiceClient->GetCompressionTypes( pBuffer, &dwSize, &dwNumElements, 0 );
    if( hr != DVERR_BUFFERTOOSMALL && FAILED(hr) )
    {
        DXTRACE_ERR_MSGBOX( TEXT("GetCompressionTypes"), hr ); 
        goto LCleanReturn;
    }

    pBuffer = new BYTE[dwSize];
    if( NULL == pBuffer )
    {
        hr = E_OUTOFMEMORY;
        DXTRACE_ERR_MSGBOX( TEXT("VoiceConfigEnumCompressionCodecs"), hr );
        goto LCleanReturn;
    }

    if( FAILED( hr = pVoiceClient->GetCompressionTypes( pBuffer, &dwSize, 
                                                        &dwNumElements, 0 ) ) )
    {
        DXTRACE_ERR_MSGBOX( TEXT("GetCompressionTypes"), hr );   
        goto LCleanReturn;
    }


    pdvCompressionInfo = (LPDVCOMPRESSIONINFO) pBuffer;
    DWORD dwIndex;
    for( dwIndex = 0; dwIndex < dwNumElements; dwIndex++ )
    {
        TCHAR strName[MAX_PATH];

        DXUtil_ConvertWideStringToGenericCch( strName, pdvCompressionInfo[dwIndex].lpszName, MAX_PATH );
        lIndex = (LONG)SendMessage( hPulldown, CB_ADDSTRING, 0, (LPARAM) strName );

        pGuid = new GUID;
        if( NULL == pGuid )
        {
            hr = E_OUTOFMEMORY;
            DXTRACE_ERR_MSGBOX( TEXT("VoiceConfigEnumCompressionCodecs"), hr );
            goto LCleanReturn;
        }

        (*pGuid) = pdvCompressionInfo[dwIndex].guidType;
        SendMessage( hPulldown, CB_SETITEMDATA, lIndex, (LPARAM) pGuid );

        if( pdvCompressionInfo[dwIndex].guidType == DPVCTGUID_SC03 )
            lFirst = lIndex;
    }

    SendMessage( hPulldown, CB_SETCURSEL, lFirst, 0 );
    hr = S_OK;

LCleanReturn:
    SAFE_RELEASE( pVoiceClient );
    SAFE_DELETE_ARRAY( pBuffer );
    
    return hr;
}




//-----------------------------------------------------------------------------
// Name: VoiceConfigDlgOnOK()
// Desc: Figure out all the DirectPlayVoice setup params from the dialog box,
//       and store them in global vars.
//-----------------------------------------------------------------------------
VOID VoiceConfigDlgOnOK( HWND hDlg )
{
    DWORD dwSliderPos;

    g_dvClientConfig.dwFlags = 0;

    // Figure out the playback params
    if( IsDlgButtonChecked( hDlg, IDC_PLAYBACK_DEFAULT ) )
    {
        g_dvClientConfig.lPlaybackVolume = DVPLAYBACKVOLUME_DEFAULT;
    }
    else 
    {
        dwSliderPos = (DWORD)SendDlgItemMessage( hDlg, IDC_PLAYBACK_SLIDER, TBM_GETPOS, 0, 0 );
        g_dvClientConfig.lPlaybackVolume = DSBVOLUME_MIN + (LONG) ( dwSliderPos / 100.0f * 
                                                                    (DSBVOLUME_MAX-DSBVOLUME_MIN) );
    }

    // Figure out the record params
    if( IsDlgButtonChecked( hDlg, IDC_RECORD_AUTO ) )
    {
        g_dvClientConfig.lRecordVolume = 0;
        g_dvClientConfig.dwFlags       |= DVCLIENTCONFIG_AUTORECORDVOLUME;
    }
    else if( IsDlgButtonChecked( hDlg, IDC_RECORD_DEFAULT ) )
    {
        g_dvClientConfig.lRecordVolume = DVPLAYBACKVOLUME_DEFAULT;
    }
    else 
    {
        dwSliderPos = (DWORD)SendDlgItemMessage( hDlg, IDC_RECORD_SLIDER, TBM_GETPOS, 0, 0 );
        g_dvClientConfig.lRecordVolume = DSBVOLUME_MIN + (LONG) ( dwSliderPos / 100.0f * 
                                                                  (DSBVOLUME_MAX-DSBVOLUME_MIN) );
    }

    // Figure out the threshold params
    if( IsDlgButtonChecked( hDlg, IDC_THRESHOLD_AUTO ) )
    {
        g_dvClientConfig.dwThreshold = DVTHRESHOLD_UNUSED;
        g_dvClientConfig.dwFlags       |= DVCLIENTCONFIG_AUTOVOICEACTIVATED;
    }
    else if( IsDlgButtonChecked( hDlg, IDC_THRESHOLD_DEFAULT ) )
    {
        g_dvClientConfig.dwThreshold = DVTHRESHOLD_DEFAULT;
        g_dvClientConfig.dwFlags       |= DVCLIENTCONFIG_MANUALVOICEACTIVATED;
    }
    else 
    {
        dwSliderPos = (DWORD)SendDlgItemMessage( hDlg, IDC_THRESHOLD_SLIDER, TBM_GETPOS, 0, 0 );
        g_dvClientConfig.dwThreshold = dwSliderPos;
        g_dvClientConfig.dwFlags       |= DVCLIENTCONFIG_MANUALVOICEACTIVATED;
    }

    if( g_bHostPlayer )
    {
        // Figure out the compression codec
        LONG lCurSelection;
        LPGUID pGuidCT;

        lCurSelection = (LONG)SendDlgItemMessage( hDlg, IDC_COMPRESSION_COMBO, CB_GETCURSEL, 0, 0 );
        if( lCurSelection != CB_ERR )
        {
            pGuidCT = (LPGUID) SendDlgItemMessage( hDlg, IDC_COMPRESSION_COMBO, 
                                                   CB_GETITEMDATA, lCurSelection, 0 );
            if( pGuidCT != NULL )
                g_guidDVSessionCT = (*pGuidCT);
        }
    }

    EndDialog( hDlg, IDOK );
}




//-----------------------------------------------------------------------------
// Name: RefreshStatusBarText()
// Desc: Refresh the current status bar text based on connection state
//-----------------------------------------------------------------------------
HRESULT RefreshStatusBarText( DPNID idLocal, DPNID idHost )
{
    HRESULT hr = S_OK; 
    TCHAR strStatus[ 1024 ] = {0};
    TCHAR strAddress[ 256 ] = {0};
    DWORD dwNumAddresses = 0; // Count of address objects
    LPDIRECTPLAY8ADDRESS *rpAddresses = NULL; // Range of addresses    
    DWORD i = 0; // Loop variable

    // Margin the status text
    _tcsncpy( strStatus, TEXT("   "), 1023 );
    strStatus[ 1023 ] = 0;

    if( idLocal == NULL || idHost == NULL )
    {
        // If the host or local dpnid is not set, this should mean the player
        // creation messages have not yet arrived
        _tcsncat( strStatus, TEXT("Not connected"), 1023 - lstrlen( strStatus ) );
        strStatus[ 1023 ] = 0;
        dwNumAddresses = 0;
    }
    else if( idLocal == idHost )
    {
        // Else if the host and local dpnid's are equal, the local player is
        // the session host
        _tcsncat( strStatus, TEXT("Hosting"), 1023 - lstrlen( strStatus ) );
        strStatus[ 1023 ] = 0;
        dwNumAddresses = 0;

        // Determine the buffer size needed to hold the addresses
        hr = g_pDP->GetLocalHostAddresses( rpAddresses, &dwNumAddresses, 0 );
        if( DPNERR_BUFFERTOOSMALL != hr )
            goto LCleanReturn;  

        // Allocate the array
        rpAddresses = new LPDIRECTPLAY8ADDRESS[ dwNumAddresses ];
        if( NULL == rpAddresses )
        {
            hr = E_OUTOFMEMORY;
            goto LCleanReturn;
        }

        ZeroMemory( rpAddresses, dwNumAddresses * sizeof(LPDIRECTPLAY8ADDRESS) );

        // Retrieve the addresses
        hr = g_pDP->GetLocalHostAddresses( rpAddresses, &dwNumAddresses, 0 );
        if( FAILED(hr) )
            goto LCleanReturn;  
    }
    else
    {
        // Else the local player is connected to a remote session
        _tcsncat( strStatus, TEXT("Connected"), 1023 - lstrlen( strStatus ) );
        strStatus[ 1023 ] = 0;
        dwNumAddresses = 1;

        // Allocate the array
        rpAddresses = new LPDIRECTPLAY8ADDRESS[ dwNumAddresses ];
        if( NULL == rpAddresses )
        {
            hr = E_OUTOFMEMORY;
            goto LCleanReturn;
        }

        ZeroMemory( rpAddresses, dwNumAddresses * sizeof(LPDIRECTPLAY8ADDRESS) );

        // Retrieve the address
        hr = g_pDP->GetPeerAddress( idHost, &rpAddresses[0], 0 );
        if( FAILED(hr) )
            goto LCleanReturn;
    }

    // If we have addresses to report, determine a reasonable way to output them
    if( dwNumAddresses > 0 )
    {
        // Get the provider from the DirectPlay address
        GUID guidSP;
        hr = rpAddresses[0]->GetSP( &guidSP );
        if( FAILED(hr) )
            goto LCleanReturn;

        TCHAR strProvider[ 256 ] = {0};
  
        if( CLSID_DP8SP_IPX == guidSP )
            _tcsncpy( strProvider, TEXT(" via IPX"), 256 );
        else if( CLSID_DP8SP_TCPIP == guidSP )
            _tcsncpy( strProvider, TEXT(" via TCP/IP"), 256 );
        else if( CLSID_DP8SP_MODEM == guidSP )
            _tcsncpy( strProvider, TEXT(" via Modem"), 256 );
        else if( CLSID_DP8SP_SERIAL == guidSP )
            _tcsncpy( strProvider, TEXT(" via Serial"), 256 );
        else if( CLSID_DP8SP_BLUETOOTH == guidSP )
            _tcsncpy( strProvider, TEXT(" via Bluetooth"), 256 );
        
        _tcsncat( strStatus, strProvider, 1023 - lstrlen( strStatus ) );
        strStatus[ 1023 ] = 0;

        // If we are using TCP/IP or IPX, display the address list
        if( CLSID_DP8SP_IPX == guidSP ||
            CLSID_DP8SP_TCPIP == guidSP )
        {
            // Append the addresses to the status text
            for( i=0; i < dwNumAddresses; i++ )
            {
                // Get the IP address
                if( FAILED( GetHostnamePortString( strAddress, rpAddresses[ i ], 256 ) ) )
                    break;

                // Add formatting characters
                TCHAR* strSpacing = ( i != 0 ) ? TEXT(", ") : 
                                    ( idLocal == idHost ) ? TEXT(" at ") : TEXT(" to ");                      
        
                _tcsncat( strStatus, strSpacing, 1023 - lstrlen( strStatus ) );
                strStatus[ 1023 ] = 0;


                // Add the IP address string
                _tcsncat( strStatus, strAddress, 1023 - lstrlen( strStatus ) );
                strStatus[ 1023 ] = 0;
     
            }
        }
    }

    // Margin the status text
    _tcsncat( strStatus, TEXT("   "), 1023 - lstrlen( strStatus ) );
    strStatus[ 1023 ] = 0;

    // Set the text
    SendDlgItemMessage( g_hDlg, IDC_STATUS_BAR_TEXT, WM_SETTEXT, 0, (LPARAM) strStatus );
    hr = S_OK;
  
LCleanReturn:
    for( i=0; i < dwNumAddresses; i++ )
        SAFE_RELEASE( rpAddresses[i] );

    SAFE_DELETE_ARRAY( rpAddresses );

    return hr;
}




//-----------------------------------------------------------------------------
// Name: GetHostnamePortString
// Desc: Stores the hostname and port number of the given DirectPlay 
//       address in the provided string.
//-----------------------------------------------------------------------------
HRESULT GetHostnamePortString( TCHAR* str, LPDIRECTPLAY8ADDRESS pAddress, DWORD dwBufferLen )
{
    HRESULT hr = S_OK;

    // Sanity check
    if( NULL == str || NULL == pAddress )
        return E_FAIL;

    // Get the hostname string from the DirectPlay address
    WCHAR wstrHostname[ 256 ] = {0};
    DWORD dwSize = sizeof(wstrHostname);
    DWORD dwDataType = 0;
    hr = pAddress->GetComponentByName( L"hostname", wstrHostname, &dwSize, &dwDataType );
    if( FAILED(hr) )
        return hr;

    // Convert from wide character to generic
    TCHAR strHostname[ 256 ] = {0};
    DXUtil_ConvertWideStringToGenericCch( strHostname, wstrHostname, 256 );

    // Get the port value from the DirectPlay address
    DWORD dwPort = 0;
    dwSize = sizeof(DWORD);
    hr = pAddress->GetComponentByName( L"port", &dwPort, &dwSize, &dwDataType );
    if( FAILED(hr) )
        return hr;

    // Copy the address string and null terminate the result
    _sntprintf( str, dwBufferLen, TEXT("%s:%d"), strHostname, dwPort );
    str[ dwBufferLen-1 ] = TEXT('\0');

    return S_OK;
}
