#include "stdafx.h"

#ifdef _MSVC_INTEL
#pragma warning(disable:4201) //Allow nameless struct
#include <mmsystem.h>
#pragma warning(default:4201)
#endif


#ifdef _LINUX
# include <sys/time.h>
# include <ctype.h>
# include "Types.h"
#endif

#include <stdio.h>

#include "UI.h"
#include "Objects.h"
#include "Dispatch.h"
#include "CSB.h"
#include "Data.h"

void EnqueMouseClick(i32, i32, i32);
void  TAG001afe(i32, i32, i32);
i32 AddSD(char *, i32, float, float, float);
void ItemsRemaining(int mode);
char *parentFolder(char *folderName, char *endName);

extern int WindowHeight;
extern int WindowWidth;
extern int WindowX;
extern int WindowY;
extern bool fullscreenRequested;
extern bool fullscreenActive;

extern i32 VBLperTimer;
extern i32 VBLMultiplier;
extern i32 screenSize;
extern i32 keyboardMode;
extern i16 trace;
void PlayfileOpen(bool);
void RecordfileOpen(bool);
extern bool BeginRecordOK;
extern bool TimerTraceActive;
extern bool AttackTraceActive;
extern bool RepeatGame;
extern i32 NoSpeedLimit;
bool OpenTraceFile(void);
void CloseTraceFile(void);
extern bool cursorIsShowing;

extern HWND hWnd;
extern HDC hdc;

#define maxMessageStack 20
CSB_UI_MESSAGE msgStack[maxMessageStack];
i32 msgStackLen = 0;
i32 messageMask = 1; //Right now just 0 or 1

i32 latestScanp1 = 0;
i32 latestScanp2 = 0;
XLATETYPE latestScanType = TYPEIGNORED;
i32 latestScanXlate = 0;
XLATETYPE latestCharType = TYPEIGNORED;
i32 latestCharp1 = 0;
i32 latestCharXlate = 0;
char playFileName[80] = "Playfile.log";
char *PlayfileName = playFileName;
char dungeonname[80] = "dungeon.dat";
char *dungeonName = dungeonname;
bool PlaybackCommandOption = false;


i32 keyQueueStart=0; // Next key to process
i32 keyQueueEnd=0;   // Next Empty entry
i32 keyQueueLen=3;
i32 keyQueue[3];


class KEYXLATE 
{
private:
  i32 m_numkey;
  i32 *m_xlate;
public:
  KEYXLATE(void)
  {
    m_numkey=0;
    m_xlate=NULL;
  };
  ~KEYXLATE(void)
  {
    if (m_xlate!=NULL) UI_free(m_xlate);
    m_xlate = NULL;
  };
  void addkey(i32 scan, i32 key, i32 mode, XLATETYPE type);
  i32 translate(i32 scan, i32 mode, XLATETYPE type);
};

void KEYXLATE::addkey(i32 scan, i32 key, i32 mode, XLATETYPE type)
{
  m_xlate = (i32 *)realloc(m_xlate, 16*(m_numkey+1));
  m_xlate[m_numkey*4+0] = scan;
  m_xlate[m_numkey*4+1] = key;
  m_xlate[m_numkey*4+2] = mode;
  m_xlate[m_numkey*4+3] = type;
  m_numkey++;
}

i32 KEYXLATE::translate(i32 scan, i32 mode, XLATETYPE type)
{
  for (i32 i=0; i<m_numkey; i++)
  {
    if (   (m_xlate[4*i+0] == scan)
        && (m_xlate[4*i+2] == mode) 
        && (m_xlate[4*i+3] == type) ) return m_xlate[4*i+1];
  };
  return 0;
}

KEYXLATE keyxlate;

char *getfield(char *buf, i32& col)
{
  static char result[200];
  char term;
  i32 len = 0;
  term = ' ';
  while (buf[col] != '\n')
  {
    if ((buf[col]!=' ') && (buf[col]!='\t')) break;
    col++;
  };
  if (buf[col] == '"')
  {
    term = '"';
    col++;
  };
  while (buf[col] != '\n')
  {
    if (   (buf[col]==term) 
        || ((term==' ') && (buf[col]=='\t'))) break;
    result[len++] = buf[col];
    if (len>198) len--;
    col++;
  };
  result[len]=0;
  return result;
}

i32 gethex(char *buf, i32& col)
{
  i32 result;
  char *field;
  field = getfield(buf,col);
  sscanf(field,"%x", &result);
  return result;
}

i32 AddSmartDiscard(char *buf)
{
  char fld[10][200];
  i32 i, j, col=0;
  i32 minimum;
  float level,y_intercept,slope;
  char *pfld;
  for (i=0; i<10; i++)
  {
    pfld=getfield(buf,col);
    if (*pfld == 0) break;
    strcpy(fld[i],pfld);
  };
  j=1;
  while (i>5)
  {
    if ((fld[j][0]>='A') && (fld[j][0]<='Z'))
    {
      strcat(fld[0]," ");
      strcat(fld[0],fld[j]);
      j++;
      i--;
    }
    else break;
  };
  if (i<5) return 1; //error
  if (sscanf(fld[j],"%d",&minimum)!=1) return 1;
  if (sscanf(fld[j+1],"%f",&level)!=1) return 1;
  if (sscanf(fld[j+2],"%f",&y_intercept)!=1) return 1;
  if (sscanf(fld[j+3],"%f",&slope)!=1) return 1;
  return AddSD(fld[0],minimum,level,y_intercept,slope);
  //return 0;
}


//************************************************************************
// Smart Discard definitions
//
//Smart Discard only operates on databases which have been enlarged
// to size 1023.  Each item in a database is given a discard priority
// which is compared to other items in the same database.  The item with
// the highest priority is discarded first.
//
// The program operates as follows:  every clock tick initiates the
// "Smart Discard" process.  The databases are considered one at a time.
// Each clock tick causes the items in a single room to be evaluated and
// added to the list.  When all rooms have been evaluated and there are
// fewer than 900 items in the database then the next database is considered.
// If more than 900 items exist then on each tick of the clock the item
// with the highest discard priority has its priority recomputed.  If it
// is still at least as great as the next higher item then it is deleted.
// On the other hand, if its priority has declined (perhaps due to party
// movement, because we just discarded an item of this type, etc) then it 
// is put back in the list in its proper place and we wait for the next 
// clock tick.
//
// The priority calculation includes a random number between 0.0 and 1.0
// so that items with the same basic priority will be randomly selected.
//
// Format:
//
//   name  minimum  level  y-intercept  slope
//
//     name         item name - blanks are allowed  (or "default") (case-insensitive)
//     minimum      integer - If this many or fewer of the item exist then
//                            none will be considered for discard.
//     level        float - additional priority for not being on a level 
//                          adjacent to the party.
//     y-intercept  float - discard priority for minimum
//     slope        float - additional discard priority for each item over minimum
//
// The item's deletion priority is  y-intercept + slope*(num-minimum) + level
//     
// Let us provide an example:
//
// example   -->  Discard   Worm Round  20  10.0  0  1
//
// Worm Rounds are not considered for deletion unless there are more than
// 20 of them in the dungeon.  Assume there are 30 of them in the dungeon.
// The discard priority for each of the 30 Worm Rounds is equal to:
//         0 + 1*(30-20).
// Each Worm Round which is on a level not immediately adjacent to the party
// will have 10.0 added to its priority.
//
//
char *SmartDiscards[] = {
"default       30  50  20.0   1.0",
"Wooden Shield 10  50  20.0   1.0", // We hardly need more than 10 of these 
"Rock          10  50  20.0   1.0",
"Sword         10  50  20.0   1.0",
"Dagger        10  50  20.0   1.0",
"Falchion      10  50  20.0   1.0",
"Club          10  50  20.0   1.0",
"Stone Club    10  50  20.0   1.0",
"Armet         10  50  20.0   1.0",
"Torso Plate   10  50  20.0   1.0",
"Leg Plate     10  50  20.0   1.0",
"Foot Plate    10  50  20.0   1.0",
//; Miscellaneous items
"Boulder       20  50  70.0   1.0", // Be sure Boulders go before food
"Dragon Steak 150   0  20.0   0.0", // Default goes before Dragon Steak.
 NULL
};

#ifdef _LINUX
#define strupr( a ) _strupr( a )
static void _strupr(char *str) {
    if( str ) {
	while(*str) {
	    *str = toupper( *str );
	    str++;
	}
    }
}
#endif
void ReadConfigFile(void)
{
  char buf[501];
  i16 f;
  i32 lineNumber = 0;
  i32 col, numerror=0;
  char *field;
  i32 scancode, key, mode;
  for (int i=0; SmartDiscards[i] != NULL; i++)
  {
    _strupr(SmartDiscards[i]);
    if (AddSmartDiscard(SmartDiscards[i]) == 0) continue;
  };
  f=OPEN("config.txt", "r");
  if (f < 0) return;
  while (GETS(buf,500,f) != NULL)
  {
    lineNumber++;
    col=0;
    if (buf[0] == ';') continue;
    field=getfield(buf,col);
    _strupr(field);
    if (strcmp(field, ";")==0) continue;
    if (strcmp(field, "") ==0) continue;
    if (strcmp(field, "KEY")==0)
    {
      mode    =gethex(buf,col);
      scancode=gethex(buf,col);
      key     =gethex(buf,col);
      keyxlate.addkey(scancode, key, mode, TYPEKEY);
      continue;
    };
    if (strcmp(field,"SCAN")==0)
    {
      mode    =gethex(buf,col);
      scancode=gethex(buf,col);
      key     =gethex(buf,col);
      keyxlate.addkey(scancode, key, mode, TYPESCAN);
      continue;
    };
    if (strcmp(field,"MSCAN")==0)
    {
      i32 x, y;
      XLATETYPE type;
      char *button;
      mode    =gethex(buf,col);
      scancode=gethex(buf,col);
      x       =gethex(buf,col);
      y       =gethex(buf,col);
      button  =getfield(buf,col);
      _strupr(button);
      if (strcmp(button,"L")==0) type=TYPEMSCANL; else type=TYPEMSCANR;
      keyxlate.addkey(scancode, (x<<16)+y, mode, type);
      continue;
    };
    if (strcmp(field,"DIRECTORY")==0)
    {
      field = getfield(buf,col);
      if (folderName != NULL) free(folderName);
      folderName = (char *) malloc(strlen(field) + 1);
      if (folderName!=NULL)
      {
        strcpy(folderName, field);
        folderParentName = parentFolder(folderName, folderName+strlen(folderName+1));
      };
      continue;
    };
    if (strcmp(field,"PLACE") == 0)
    {
      int k, size, srcx, srcy, width, height, x, y;
      field = getfield(buf,col);
      if ( (field[0] < 'A')||(field[0] > 'E') ) continue;
      k = field[0] - 'A';
      size = gethex(buf,col);
      if ( (size < 0)||(size > 4) ) continue;
      srcx = gethex(buf,col);
      if ( (srcx<0) || (srcx>319) ) continue;
      srcy = gethex(buf,col);
      if ( (srcy<0) || (srcy>199) ) continue;
      width = gethex(buf,col);
      if ( (width<1) || (srcx+width>320) )continue;
      height = gethex(buf,col);
      if ( (height<1) || (srcy+height>200) )continue;
      x = gethex(buf,col);
      if ( (x < 0)||(x > 4096) ) continue;
      y = gethex(buf,col);
      if ( (y < 0)||(y >4096) ) continue;
      videoSegSize[k] = size;
      videoSegSrcX[k] = srcx;
      videoSegSrcY[k] = srcy;
      videoSegWidth[k] = width;
      videoSegHeight[k] = height;
      videoSegX[k] = x;
      videoSegY[k] = y;
      continue;
    };
    if (numerror==0)
    {
      char msg[200];
      if (strlen(buf)>0)
        if (buf[strlen(buf)-1] == '\n')
          buf[strlen(buf)-1] = 0;
      buf[100] = 0; //Just in case it is very long;
      sprintf(msg,"Line number = %d\n%s",lineNumber,buf);
      UI_MessageBox(msg,"Bad Config Line",MESSAGE_OK);
      numerror++;
    };
  };
  CLOSE(f);
}




i32 UI_DisableAllMessages(void)
{
  i32 oldmask = messageMask;
  messageMask = 0;
  return oldmask;
}

i32 UI_EnableMessages(i32 mask)
{
  messageMask |= mask;
  return messageMask;
}


i32 CSBUI(CSB_UI_MESSAGE *msg)
{
  i32 CallCheckVBL= 0;
  if (messageMask == 0) return UI_STATUS_NORMAL;
  try
  {
    switch (msg->type)
    {
    case UIM_INITIALIZE:
        ReadConfigFile();
        //Set the GameMode //0=quit
                           //1=dungeon
                           //2=utility
                           //3=hint
        DispatchCSB(st_AskWhatToDo);
        break;
    case UIM_SETOPTION:
      switch (msg->p1)
      {
      case OPT_DMRULES:
        DM_rules = !DM_rules;
        break;
      case OPT_NORMAL:
        UI_ClearScreen();
        screenSize = 1;
        break;
      case OPT_DOUBLE:
        UI_ClearScreen();
        if (msg->p2 == 1) screenSize = 1;
        else screenSize = 2;
        break;
      case OPT_TRIPLE:
        UI_ClearScreen();
        if (msg->p2 == 1) screenSize = 1;
        else screenSize = 3;
        break;
      case OPT_QUADRUPLE:
        UI_ClearScreen();
        if (msg->p2 == 1) screenSize = 1;
        else screenSize = 4;
        break;
      case OPT_RECORD:
        if (msg->p2 == 1) RecordfileOpen(true);
        else RecordfileOpen(false);
        break;
      case OPT_PLAYBACK:
        if (msg->p2 == 1) PlayfileOpen(true);
        else PlayfileOpen(false);
        break;
      case OPT_QUICKPLAY:
        if (msg->p2 == 1) NoSpeedLimit = 2000000000;
        else 
        {
          NoSpeedLimit = 0;
          VBLMultiplier = 1;
        };
        break;
      case OPT_CLOCK:
        gameSpeed = (SPEEDS)msg->p2;
        break;
      case OPT_PLAYERCLOCK:
        playerClock = !playerClock;
        break;
      case OPT_EXTRATICKS:
        extraTicks = !extraTicks;
        break;
      case OPT_ITEMSREMAINING:
        ItemsRemaining(0);
        break;
      case OPT_NONCSBITEMSREMAINING:
        ItemsRemaining(1);
        break;
      case OPT_TIMERTRACE:
        if (TimerTraceActive)
        {
          TimerTraceActive = false;
          if (!AttackTraceActive)
          {
            CloseTraceFile();
          };
        }
        else
        {
          if (AttackTraceActive || OpenTraceFile())
          {
            TimerTraceActive = true;
          };
        };
        break;
      case OPT_ATTACKTRACE:
        if (AttackTraceActive)
        {
          AttackTraceActive = false;
          if (!TimerTraceActive)
          {
            CloseTraceFile();
          };
        }
        else
        {
          if (TimerTraceActive || OpenTraceFile())
          {
            AttackTraceActive = true;
          };
        };
        break;
      default:
        ASSERT(0);
      };
      break;
    case UIM_TERMINATE:
        return UI_STATUS_TERMINATE; 
    case UIM_CHAR:
        {
          if ((latestCharp1 == 3) && (msg->p1 == 3))
          {
            UI_Die();
            break;
          };
          latestCharp1 = msg->p1;
          latestCharType = TYPEIGNORED;
          i32 key = keyxlate.translate(msg->p1, keyboardMode, TYPEKEY);
          if (key != 0)
          {
            i32 next = keyQueueEnd+1;
            latestCharType = TYPEKEY;
            latestCharXlate = key;
            if (next >= keyQueueLen) next=0;
            if (next != keyQueueStart)
            {
              keyQueue[keyQueueEnd]= key;
              keyQueueEnd = next;
            };
          }
        }
        break;
    case UIM_KEYDOWN:
        {
          i32 key;
          latestScanp1 = msg->p1;
          latestScanp2 = msg->p2;
          if ((key = keyxlate.translate(msg->p2&0xff, 
                                        keyboardMode, 
                                        TYPESCAN))!= 0)
          {
            latestScanType = TYPESCAN;
            latestScanXlate = key;
            i32 next = keyQueueEnd+1;
            if (next >= keyQueueLen) next=0;
            if (next != keyQueueStart)
            {
              keyQueue[keyQueueEnd]= key;
              keyQueueEnd = next;
            };
          }
          else
          if ((key = keyxlate.translate(msg->p1, keyboardMode, TYPEMSCANL))!= 0)
          {
            latestScanType = TYPEMSCANL;
            latestScanXlate = key;
            OnMouseSwitchAction(2, key>>16, key & 0xffff);
            OnMouseSwitchAction(0);
          }
          else
          if ((key = keyxlate.translate(msg->p1, keyboardMode, TYPEMSCANR))!= 0)
          {
            latestScanType = TYPEMSCANR;
            latestScanXlate = key;
            OnMouseSwitchAction(1, key>>16, key & 0xffff);
            OnMouseSwitchAction(0);
          }
          else
          {
            latestScanType = TYPEIGNORED;
          };
        }
        break;
    case UIM_TIMER:
        //The UIM_TIMER messages come no more often than
        //20 per second on my machine.  So we can cause multiple
        //VBLs per UIM_TIMER.  Our stategy is to call CheckVBL.
        //Then dispatch until nothing is left to do.  Then
        //call CheckVBL again.  Repeat entire process 10 times
        CallCheckVBL = VBLperTimer*VBLMultiplier; // do it 10 times
        if (trace > 0) 
        {
          fprintf(GETFILE(trace),"UIM_TIMER\n");
          fflush(GETFILE(trace));
        }
        break;
    case UIM_PAINT:
        display();
        break;
    case UIM_REDRAW_ENTIRE_SCREEN:
        ForceScreenDraw();
        UI_Invalidate();
        break;
    case UIM_LEFT_BUTTON_DOWN:
        OnMouseSwitchAction(0x2);
        if (fullscreenActive)
        {
          int x,y,size;
          size = screenSize;
          TranslateFullscreen(msg->p1,msg->p2,x,y);
          EnqueMouseClick(x, y, 1);
          TAG001afe(x, y, 1);
        }
        else
        {
          EnqueMouseClick(X_TO_CSB(msg->p1,screenSize), Y_TO_CSB(msg->p2,screenSize),1);
          TAG001afe(X_TO_CSB(msg->p1,screenSize), Y_TO_CSB(msg->p2,screenSize), 1);
        };
        UI_PushMessage(msg->type);
        break;
    case UIM_LEFT_BUTTON_UP:
        OnMouseSwitchAction(0x0);
        break;
    case UIM_RIGHT_BUTTON_DOWN:
        OnMouseSwitchAction(0x1);
        if (fullscreenActive)
        {
          int x, y, size;
          size = screenSize;
          TranslateFullscreen(msg->p1,msg->p2,x,y);
          EnqueMouseClick(x, y, 1);
          TAG001afe(x, y, 1); //[Erik]: Is this correct?
        }
        else
        {
          EnqueMouseClick(X_TO_CSB(msg->p1,screenSize), Y_TO_CSB(msg->p2,screenSize),1);
          TAG001afe(X_TO_CSB(msg->p2,screenSize), Y_TO_CSB(msg->p1,screenSize), 1); //[Erik]: Is this correct?
        };
        UI_PushMessage(msg->type);
        break;
    case UIM_RIGHT_BUTTON_UP:
        OnMouseSwitchAction(0x0);
        break;
    default:
      ASSERT(0);
    };
    do
    {
      if (CallCheckVBL > 0)
      {
        checkVBL();
        CallCheckVBL--;
      };
      while (msgStackLen != 0)
      {
        msgStackLen--;
        if (msgStack[msgStackLen].type == UIM_TERMINATE)
        { 
          return UI_STATUS_TERMINATE;
        };
        DispatchCSB(&msgStack[msgStackLen]);
      };
    } while (CallCheckVBL > 0);
      return UI_STATUS_NORMAL;
  }
  catch (i32)
  {
#ifdef _LINUX
      g_warning("Exception caught in: i32 CSBUI(CSB_UI_MESSAGE *msg)\n");
#endif
    return UI_STATUS_TERMINATE;
  };
};

void UI_PushMessage(MTYPE type,
                    i32 p1,i32 p2,i32 p3,i32 p4,i32 p5,i32 p6)
{
  if (msgStackLen >= maxMessageStack-1) UI_Die();
  msgStack[msgStackLen].type = type;
  msgStack[msgStackLen].p1 = p1;
  msgStack[msgStackLen].p2 = p2;
  msgStack[msgStackLen].p3 = p3;
  msgStack[msgStackLen].p4 = p4;
  msgStack[msgStackLen].p5 = p5;
  msgStack[msgStackLen].p6 = p6;
  msgStackLen++;
}
  

#ifdef _MSVC_INTEL
void UI_Invalidate()
{
    InvalidateRect(hWnd, NULL, false);
}
#endif //_MSVC_INTEL

i32 UI_DeleteFile(char *fname)
{
  return (remove(fname)==0) ? 1 : 0;;
}

#ifdef _MSVC_INTEL
i32 UI_MessageBox(char *msg, char *title, i32 flags)
{
  i32 i;
  i32 MB_FLAGS = MB_APPLMODAL | MB_TOPMOST;
  if (flags & MESSAGE_OK) MB_FLAGS |= MB_OK;
  if (flags & MESSAGE_YESNO) MB_FLAGS |= MB_YESNO;
  if (flags & MESSAGE_ICONERROR) MB_FLAGS |= MB_ICONERROR;
  if (flags & MESSAGE_ICONWARNING) MB_FLAGS |= MB_ICONWARNING;
  bool saveCursorShowing;
  saveCursorShowing = cursorIsShowing;
  if (!cursorIsShowing) ShowCursor(true);
  i32 mask = UI_DisableAllMessages();
  if (title == NULL) title = "Error";
  i = MessageBox(hWnd, msg, title, MB_FLAGS);
  UI_EnableMessages(mask);
  if (!saveCursorShowing) ShowCursor(false);
  if (i == IDYES) return MESSAGE_IDYES;
  if (i == IDNO)  return MESSAGE_IDNO;
  return MESSAGE_IDOK;
}
#endif //_MSVC_INTEL
#ifdef _LINUX
# include <gnome.h>
i32 UI_MessageBox(char *msg, char *title, i32 flags ) {
    g_warning("[%s] %s", title, msg);
    GtkWidget *dialog;
    GString *text = g_string_new(msg);
	
  i32 i=1;// default answer
    if(title==NULL){
	title="Error: \n";    
    }else{
	text = g_string_prepend(text,": \n");
    }
    
    text = g_string_prepend(text,title);
   
  bool saveCursorShowing, cursorIsShowing, is_ok=false;
  saveCursorShowing = cursorIsShowing = ( SDL_ENABLE == SDL_ShowCursor(SDL_QUERY) );
  if (!cursorIsShowing) SDL_ShowCursor(SDL_ENABLE);
  
    
  if (flags & MESSAGE_OK){
      dialog = gnome_message_box_new(text->str, GNOME_MESSAGE_BOX_INFO, GNOME_STOCK_BUTTON_OK, NULL);
      is_ok=true;
  }
    else if (flags & MESSAGE_YESNO)
      dialog = gnome_message_box_new(text->str,GNOME_MESSAGE_BOX_QUESTION, GNOME_STOCK_BUTTON_YES, GNOME_STOCK_BUTTON_NO, NULL);
    else if (flags & MESSAGE_ICONERROR)
      dialog = gnome_message_box_new(text->str,GNOME_MESSAGE_BOX_ERROR,"Die", NULL);
    else if (flags & MESSAGE_ICONWARNING)
      dialog = gnome_message_box_new(text->str,GNOME_MESSAGE_BOX_WARNING,"Close",NULL);
    
    i32 mask = UI_DisableAllMessages();
    
     i = gnome_dialog_run_and_close (GNOME_DIALOG (dialog));
     
  UI_EnableMessages(mask);
  if (!saveCursorShowing) SDL_ShowCursor(SDL_DISABLE);
  if (i == 0 && is_ok == false) return MESSAGE_IDYES; // 0 == first button pressed
  if (i == 1 || i == -1)  return MESSAGE_IDNO; // 1 == second button pressed, (-1) == if MsgBox is 'destroyed'
  return MESSAGE_IDOK;
}
#endif //_LINUX





i32 UI_CONSTAT(void)
{
  if (keyQueueStart != keyQueueEnd) return 1;
  return 0; // No console input available
}

i32 UI_DIRECT_CONIN(void)
{ //We should wait for a keystroke.  But we don't.  It is
  // up to you to be sure that input exists before
  // calling DIRECT_CONIN.
  ASSERT(keyQueueStart != keyQueueEnd);
  if (keyQueueStart == keyQueueEnd) return -1;
  i32 key = keyQueue[keyQueueStart];
  keyQueueStart++;
  if (keyQueueStart >= keyQueueLen) keyQueueStart=0;
  return key;
}

void UI_Die(void)
{
  throw 0xbad;
}

void UI_Sleep(i32 milliseconds)
{
#ifdef _MSVC_INTEL
  if (!NoSleep) Sleep(milliseconds); //Windows sleep function
#endif //_MSVC_INTEL
#ifdef TARGET_OS_MAC
  Sleep(milliseconds); 
#endif
#ifdef _LINUX
  usleep(milliseconds*1000);
#endif //_LINUX
}

#ifdef _MSVC_INTEL
void UI_PlaySound(char *wave, i32 flags)
{
  i32 sndflags;
  sndflags = 0;
  if (flags & SOUND_SYNC)  sndflags |= SND_SYNC;
  if (flags & SOUND_ASYNC) sndflags |= SND_ASYNC;
  if (flags & SOUND_MEMORY)sndflags |= SND_MEMORY;
  sndflags |= SND_ASYNC;
  sndPlaySound(wave, sndflags);
}
#endif //_MSVC_INTEL
#ifdef TARGET_OS_MAC
void UI_PlaySound(char *wave, i32 flags)
{
  i32 sndflags;
  sndflags = 0;
  if (flags & SOUND_SYNC)  sndflags |= SND_SYNC;
  if (flags & SOUND_ASYNC) sndflags |= SND_ASYNC;
  if (flags & SOUND_MEMORY)sndflags |= SND_MEMORY;
  sndflags |= SND_ASYNC;
  sndPlaySound(wave, sndflags);
}
#endif //TARGET_OS_MAC
#ifdef _LINUX
/*
static SDL_AudioSpec spec;
static GSList * sound_queue = NULL;
static guint8 * current_audio_buffer = NULL;
static int audio_to_go = 0;
static void __sound_callback(void *userdata, Uint8 *stream, int len) {
    if( audio_to_go ) {
    } else {
	GSList * node = sound_queue;
	if(node) {
	    sound_queue = node->next;
	    SDL_AudioSpec *spec = (SDL_AudioSpec*)  node->data;
	    g_slist_free_1( node );
	    current_audio_buffer = spec->
	} else {
	    // No more to play.
	    SDL_PauseAudio(TRUE);
	}
    memcpy( stream, userdata, len );
    void SDL_FreeWAV(Uint8 *audio_buf);
}
void UI_Initialize_sounds(void) {
    spec.freq=22050;
    spec.format=AUDIO_S16LSB;
    spec.samples=8192;
    spec.callback=__sound_callback;
    spec.userdata=&current;
    if ( SDL_OpenAudio(&spec,NULL) < 0 ){  fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());  exit(-1); }
    SDL_PauseAudio(FALSE);
}*/
void UI_PlaySound(char *wave, i32 flags) {
//SDL_AudioSpec *SDL_LoadWAV(const char *file, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len);
}
#endif //_LINUX

#ifdef _MSVC_INTEL
void UI_ClearScreen(void)
{
  RedrawWindow(hWnd,NULL,NULL,RDW_ERASE|RDW_INVALIDATE);
}

void UI_SetDIBitsToDevice(i32 dstX,
                          i32 dstY,
                          i32 srcWidth,
                          i32 srcHeight,
                          i32 srcX,
                          i32 srcY,
                          i32 firstScan,
                          i32 numScan,
                          char *bitmap,
                          void *bInfo,//struct tagBITMAPINFO *bInfo,
                          i32 flags)
{
  HDC newhdc;
  newhdc = 0;
  if (hdc == 0)
  {
    newhdc = GetDC(hWnd);
    hdc = newhdc;
  };
  SetDIBitsToDevice(hdc,
                    dstX,
                    dstY,
                    srcWidth,
                    srcHeight,
                    srcX,
                    srcY,
                    firstScan,
                    numScan,
                    bitmap,
                    (tagBITMAPINFO *)bInfo,
                    flags);
  if (newhdc != 0)
  {
    ReleaseDC(hWnd,newhdc);
    hdc = 0;
  };
}
#endif

#ifndef _LINUX
// The linux version of this function is defined in CSBlinux.cpp
void UI_GetCursorPos(i32 *x, i32 *y)
{
  POINT point;
  GetCursorPos(&point);
  ScreenToClient(hWnd,&point);
  if (fullscreenActive)
  {
    int x, y;
    TranslateFullscreen(point.x,point.y,x,y);
    point.x = x;
    point.y = y;
  }
  else
  {
    point.x = (point.x + screenSize/2)/screenSize;
    point.y = (point.y + screenSize/2)/screenSize;
  };
  if (point.x < 0) point.x = 0;
  if (point.y < 0) point.y = 0;
  *x = point.x;
  *y = point.y;
}
#endif

bool UI_ProcessOption(char *key, char *value)
{
  if (strcmp(key,"DIRECTORY")==0)
  {
    if (folderName != NULL) free(folderName);
    folderName = (char *)malloc(strlen(value)+2);
    if (folderName != NULL) 
    {
      strcpy(folderName,value);
      if (folderName[strlen(folderName)-1] != '\\')
      {
        folderName[strlen(folderName)+1] = 0;
        folderName[strlen(folderName)] = '\\';
      };
      if (folderParentName != NULL) free(folderParentName);
      folderParentName = parentFolder(folderName, folderName+strlen(folderName));
    };
    return true;
  };
  if (strcmp(key,"REPEAT") == 0)
  {
    RepeatGame = true;
    return true;
  };
  if (strcmp(key,"HEIGHT") == 0)
  {
    sscanf(value,"%d", &WindowHeight);
    return true;
  };
  if (strcmp(key,"QUICK") == 0)
  {
    sscanf(value,"%d", &NoSpeedLimit);
    return true;
  };
  if (strcmp(key,"VBLMULTIPLIER") == 0)
  {
    sscanf(value,"%d", &VBLMultiplier);
    return true;
  };
  if (strcmp(key,"DUNGEON") == 0)
  {
    strcpy(dungeonName,value);
    return true;
  };
  if (strcmp(key,"WIDTH") == 0)
  {
    sscanf(value,"%d", &WindowWidth);
    return true;
  };
  if (strcmp(key,"X") == 0)
  {
    sscanf(value,"%d", &WindowX);
    return true;
  };
  if (strcmp(key,"Y") == 0)
  {
    sscanf(value,"%d", &WindowY);
    return true;
  };
  if (strcmp(key,"SIZE") == 0)
  {
    strupr(value);
    if (strcmp(value,"FULL") == 0)
    {
      fullscreenRequested = true;
    };
    if (strcmp(value,"EXTRALARGE") == 0)
    {
      screenSize = 4;
      return true;
    };
    if (strcmp(value,"VERYLARGE") == 0)
    {
      screenSize = 3;
      return true;
    };
    if (strcmp(value,"LARGE") == 0)
    {
      screenSize = 2;
      return true;
    };
    if (strcmp(value,"SMALL") == 0)
    {
      screenSize = 1;
      return true;
    };
    return false;
  };
  if (strcmp(key,"PLAY") == 0)
  {
    strcpy(PlayfileName,value);
    extraTicks = false;
    PlaybackCommandOption = true;
    return true;
  };
  return false;
}

void UI_BeginRecordOK(bool ok)
{
  BeginRecordOK = ok;
  if (ok)
  {
    if (PlaybackCommandOption)
    {
      PlayfileOpen(true);
    };
  };
}

char *parentFolder(char *filename, char *endname)
{
  char *result=NULL;
  // filename points to first character; endname points to last+1;
  // Now we back up, looking for a '\'
#ifdef _MSVC_INTEL
  if (*(endname-1) == '\\') endname--;
  while (endname > filename)
  {
    endname--;
    if (*endname == '\\') break;
  };
 #endif
 #ifdef _LINUX
   if (*(endname-1) == '/') endname--;
  while (endname > filename)
  {
    endname--;
    if (*endname == '/') break;
  };
#endif
  if (endname > filename)
  {
    endname++; //include the backslash at the end
    result = (char *)malloc(endname-filename+1);
    if (result != NULL)
    {
      memcpy(result,filename,endname-filename);
      result[endname-filename] = 0;
    };
  };
  return result;
}

#ifdef _MSVC_INTEL
i64 UI_GetSystemTime(void)
{
  // Cumulative milliseconds since 1980 (or whenever..not important)
  SYSTEMTIME st;
  i64 result;
  i32 Day;
  GetSystemTime(&st);
  if (st.wMonth < 3)
  {
    st.wYear--;
    st.wMonth += 12;
  };
  Day = st.wDay;
  Day += 365 * st.wYear;
  Day += st.wYear/4;//We won't worry about -year/400 ;-)
  Day += 30 * st.wMonth;
  Day += (3 * (st.wMonth + 1))/5;
  result = Day;
  result *= 24;
  result += st.wHour;
  result *= 60;
  result += st.wMinute;
  result *= 60;
  result += st.wSecond;
  result *= 1000;
  result += st.wMilliseconds;
  return result;
}
#endif //_MSVC_INTEL
#ifdef _LINUX
i64 UI_GetSystemTime(void)
{
    struct timeval t;
    gettimeofday( &t, NULL );
    return ((guint32) t.tv_usec)/1000 + ((guint64) t.tv_sec)*1000;
}	
#endif //_LINUX

#if defined _MSVC_INTEL || defined _LINUX
FILE *UI_fopen(char *name, char *flags)
{
  return fopen(name, flags);
}
#endif //_MSVC_INTEL||_LINUX


void *UI_malloc(i32 size)
{
#if defined _MSVC_INTEL || defined _LINUX
  return malloc(size);
#endif //_MSVC_INTEL||_LINUX
#ifdef macintosh
  xxxxx
#endif
}

#if defined _MSVC_INTEL || defined _LINUX
void UI_free(void *buf)
{
  free(buf);
}
#endif //_MSVC_INTEL||_LINUX
