
#include <Tapwave.h>
//#include <PalmOS.h>
#include <VfsMgr.h>
//#include <PalmOSGlue.h>
#include "StarterRsc.h"

#include "endianutils.h"
#include "host68k.h"

#include "zodiac.h"

TwGfxType *lib = NULL;
TwGfxInfoType ginfo;

#if 0
extern Call68KFuncType * g_my_call68KFuncP;
extern const void *g_my_emulStateP;

struct TwGlue*   twGlue;
const void*      twEmulState;
Call68KFuncType* twCall68KFunc;
#endif

UInt8 g_zodiac = 0;
TwGfxSurfaceType *g_display_surface;
TwGfxSurfaceType *g_backbuffer_surface;

UInt8 tw_gfx_init ( void ) {
  Err error;
  TwGfxSurfaceInfoType surfInfo;

  // prepare TW necessities..
#if 0
  twGlue = MemPtrNew ( sizeof(struct TwGlue)*2 );
  twEmulState = g_my_emulStateP;
  twCall68KFunc = g_my_call68KFuncP;
#endif

  // prepare for call
  ginfo.size = sizeof(ginfo);

  // set up the API
  error = TwGfxOpen ( &lib, &ginfo );

  if ( error ) {
    return ( 0 );
  }

  // get physical display surface
  error = TwGfxGetDisplaySurface ( lib, &g_display_surface );

  if ( error ) {
    return ( 0 );
  }

  // create a backbuffer surface (to blit from)
  surfInfo.size = sizeof(surfInfo);
  surfInfo.width = ginfo.displayWidth;
  surfInfo.height = ginfo.displayHeight;
  surfInfo.location = twGfxLocationAcceleratorMemory;
  surfInfo.pixelFormat = twGfxPixelFormatRGB565;
  error = TwGfxAllocSurface ( lib, &g_backbuffer_surface, &surfInfo );

  if ( error ) {
    return ( 0 );
  }

  return ( 1 );
}

void tw_gfx_close ( void ) {

  // free backbuffer
  TwGfxFreeSurface ( g_backbuffer_surface );

  // release lib
  TwGfxClose ( lib );

  return;
}

void tw_gfx_blit ( void ) {
  Err error;

  // bounds
  TwGfxPointType zeropoint;
  TwGfxRectType rect;   // source
  TwGfxRectType drect;  // destination

  zeropoint.x = 0;
  zeropoint.y = 0;

  rect.x = 0;
  rect.y = 32;
  rect.w = 320;
  rect.h = 240;

  drect.x = 0;
  drect.y = 0;
  drect.w = ginfo.displayWidth;
  drect.h = ginfo.displayHeight;

  // blit backbuffer to screen
  TwGfxStretchBlt2 ( g_display_surface, &drect,
		     g_backbuffer_surface, &rect,
		     twGfxStretchFast | twGfxStretchSmooth );

  return;
}

Boolean TwCheckAPIVersion ( UInt32 minVersion ) {
  UInt32 version;
  FtrGet ( twFtrCreator, twFtrAPIVersion, &version );
  return ( version >= minVersion );
}

UInt8 is_zodiac ( void ) {

  if ( TwCheckAPIVersion ( TAPWAVE_API_VERSION ) ) {
    return ( 1 );
  }

  return ( 0 );
}

UInt32 tw_gfx_lock ( void ) {
  void *x;
  Err error;

  error = TwGfxLockSurface ( g_backbuffer_surface, &x );

  if ( error ) {
    return ( NULL );
  }

  return ( (UInt32) x );
}

void tw_gfx_unlock ( void ) {
  TwGfxUnlockSurface ( g_backbuffer_surface, true );
  return;
}
