// C++ code Copyright (C) David R. Evans G4AMJ/NQ0I

// definitions for Windows
#include <DREstring.h>
#include <windows.h>

// define a handler for fatal error

void _FE(const char* cp, const char* file, const int line)
{ //trace(cp);
  char temp1[100], temp2[10];
  strcpy(temp1, cp);
  if (*cp) then
    strcat(temp1, " -- ");
  strcat(temp1, file);
  strcat(temp1, " : ");
  strcat(temp1, itoa(line, temp2, 10));
  MessageBox(NULL, temp1, "FATAL ERROR", MB_OK);
  exit(-2);
}

// define a handler for nonfatal error
void _NFE(const char* cp, const char* file, const int line)
{ //trace(cp);
  char temp1[100], temp2[10];
  strcpy(temp1, cp);
  if (*cp) then
    strcat(temp1, " -- ");
  strcat(temp1, file);
  strcat(temp1, " : ");
  strcat(temp1, itoa(line, temp2, 10));
  strcat(temp1, "\n     CONTINUE?");
  if (MessageBox(NULL, temp1, "NONFATAL ERROR", MB_YESNO) == IDNO) then
    exit(-2);
}

// define a handler to check an upcoming request for space; not all compilers
// for Intel chips like allocating > 64K at a time

void _CST(const unsigned long size, const unsigned long number,
         const char* file, const int line)
{ if (size * number > 65000L) then
    _FE("Attempt to allocate > 64K", file, line);
}

// byte inversion routines
void _invert(uint16& ui16)
{ byte* b = (byte*)(void*)&ui16;
  register byte t = b[0];
  b[0] = b[1];
  b[1] = t;
}

/*void invert(int32& i32)
{ int16* i16 = (int16*)(void*)&i32;
  invert(i16[0]);
  invert(i16[1]);
}*/

// a generic logging facility
void _TRACELOG(const char* msg, const char* file, const int line)
{ char temp[100];
  itoa(line, temp, 10);
  trace_log << msg << " (" << file << ":" << temp << ")" << endl << flush;
}

// provide a Windows yield function
void yield(void)
{ static MSG msg;
  const int n_to_process = 4;

// one cannot use a while loop because WM_PAINTs are never removed
  for (int n = 0; n < n_to_process; n++)
  { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
    { TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
  }
}
