#include <Winten.h>
#include <Windows.h>
#include <ClipApi.h>

extern HGLOBAL   _SetAcceleratorTable( HGLOBAL hAccelTable );
extern HGLOBAL   _fwAddGlobal( HGLOBAL );
extern HGLOBAL   fwGlobalAlloc( WORD, LONG );
extern HGLOBAL   fwGlobalReAlloc( HGLOBAL, LONG, WORD );
extern WORD      GetWndApp( void );

#define CHUNK  6

typedef struct
{
    BYTE bFlags;
    WORD wEvent;
    WORD wId;
} ACCELENTRY;

typedef ACCELENTRY far * LPACCELENTRY;

#define ACC_SHIFT   0x04
#define ACC_CONTROL 0x08
#define ACC_ALT     0x10

static WORD wAccSize  = 0;
static WORD wAccCount = 0;

//---------------------------------------------------------------------------//

WORD wAccelTableLen( LPACCELENTRY pTable )
{
    WORD wIndex = 0;

    while( !( pTable[ wIndex++ ].bFlags & 0x80 ) );

    if( pTable[ wIndex - 1 ].wEvent )
        return wIndex;
    else
        return 0xFFFF;

}

//---------------------------------------------------------------------------//

CLIPPER __AddAccel( void ) // ( nState, nVirtKey, nId )
{

    HGLOBAL hAccel;
    LPACCELENTRY pTable;

    if( ! wAccSize )
    {
        hAccel = _fwAddGlobal( fwGlobalAlloc( GHND,  CHUNK * sizeof( ACCELENTRY ) ) );
        wAccSize  = CHUNK;
        _SetAcceleratorTable( hAccel );
    }
    else
        hAccel = _SetAcceleratorTable( 0 );


    if( hAccel )
    {
        if( wAccCount == wAccSize )
        {
            wAccSize += CHUNK;
            hAccel = fwGlobalReAlloc( hAccel, wAccSize * sizeof( ACCELENTRY ), GHND );
            _SetAcceleratorTable( hAccel );
        }

		pTable = (LPACCELENTRY) GlobalLock( hAccel );

        pTable[ wAccCount ].bFlags = (BYTE) ( _parni( 1 ) | 0x0001 );
        pTable[ wAccCount ].wEvent = _parni( 2 );
        pTable[ wAccCount ].wId    = _parni( 3 );

        // End OF Table
        if( wAccCount )
            pTable[ wAccCount - 1 ].bFlags ^= 0x80;

        pTable[ wAccCount ].bFlags |= 0x80;

        wAccCount++;

		GlobalUnlock( hAccel );

	}

}

//---------------------------------------------------------------------------//
