#include <vectrex.h>

#define int8_t  int
#define uint8_t unsigned int
#define int16_t long
#define uint16_t unsigned long
#define int32_t long long
#define uint32_t unsigned long long

#ifndef TRUE
#define TRUE (0==0)
#define FALSE (0!=0)
#endif

#define NULL 0

static unsigned int dotmask = 0xC3;

#define DRAWING_SCALE 0x80
#define CROSSHAIR_SCALE 0x40

#define set_scale(s) do { VIA_t1_cnt_lo = s; } while (0)
#define BRIGHT TRUE
#define normal FALSE

static unsigned char patList[2];
static void drawline_patterned (int y, int x, unsigned char pat)
{
   patList[0] = (unsigned char) y;
   patList[1] = (unsigned char) x;
   *(volatile unsigned char *) 0xC829 = pat;
   *(volatile unsigned char *) 0xC823 = 0;
   Draw_Pat_VL (patList);
}

static int last_intensity = -128;
static void
drawline (unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2,
	  int bright, int dashed)
{
   long ax1, ay1, dx, dy;

   if (bright) {
      if (last_intensity != BRIGHT)
	 Intensity_7F ();
   } else {
      if (last_intensity != normal)
	 Intensity_3F ();
   }
   last_intensity = bright;
   Reset0Ref ();
   set_scale (DRAWING_SCALE);
   ax1 = ((long) x1 - 128L);
   ay1 = ((long) y1 - 128L);
   dx = ((long) x2 - (long) x1);
   dy = ((long) y2 - (long) y1);

   Moveto_d ((int) ay1, (int) ax1);

   // id dx is 255, it splits into 127 and 128 - which causes a problem
   // because +128 is not possible
   if (dy == 255 || dx == 255) {
      // 255-unit long lines are split in three, all others are split in two.
      drawline_patterned ((int) (dy / 3L), (int) (dx / 3L),
			  (dashed ? dotmask : 0xFF));
      dy -= dy / 3L;
      dx -= dx / 3L;
   }
   if (dy < -128L || dy > 127L || dx < -128L || dx > 127L) {
      drawline_patterned ((int) (dy >> 1L), (int) (dx >> 1L),
			  (dashed ? dotmask : 0xFF));
      // don't care which way it rounds (>>1 or /2) because this picks up the 
      // odd bit:
      dy -= dy >> 1L;
      dx -= dx >> 1L;
   }
   drawline_patterned ((int) dy, (int) dx, (dashed ? dotmask : 0xFF));
}

static char *mystrdup (const char *s)
{
   // to ensure writable strings in 'assign' procedure
   // No heap on vectrex, so this is a little hacky.
   // Fortunately I know we never have more than
   // one 'heap' string at a time...
   static char copy[255U], *t;	// has to be large enough for biggest problem 
				// string in layouts.h
   unsigned int len;

   t = copy;
   len = 0;
   do {
      len += 1;
      if (len == 255) {
	 for (;;) ;		// halt.
      }
      *t++ = *s++;
   }
   while (*s != '\0');
   *t = '\0';
   return copy;
}

static char *mystrchr (char *s, char ch)
{
   if (!s)
      return NULL;
   for (;;) {
      if (*s == '\0')
	 return NULL;
      if (*s == ch)
	 return s;
      s += 1;
   }
}

static int atoui (const char *s)
{				// we know all inputs are unsigned
   int i = 0, c;

   if (!s)
      return i;
   for (;;) {
      if (*s == '\0')
	 return i;
      c = (int) *s++;
      if (c < '0')
	 break;
      if (c > '9')
	 break;
      c = c - '0';
      i = i * 10 + c;
   }
   return i;
}

static uint8_t _x, _a, _b, _c;
static void
initRandom (unsigned int s1, unsigned int s2, unsigned int s3,
	    unsigned int x0)
{
   _x = x0;
   _a = s1;
   _b = s2;
   _c = s3;
   _x++;
   _a = (_a ^ _c ^ _x);
   _b = (_b + _a);
   _c = ((_c + (_b >> 1)) ^ _a);
}

static uint8_t random8 (void)
{				// assert returns unsigned value that fits in 
				// an int.
   _x++;
   _a = (_a ^ _c ^ _x);
   _b = (_b + _a);
   _c = ((_c + (_b >> 1)) ^ _a);
   return _c;
}

#define IRQ_6809_MASK 0x10
#define ENABLE_IRQ_6809 asm("andcc #0xef")
#define DISABLE_IRQ_6809 asm("orcc #0x10")

// does not return, since we use the
// actual waitRecal "shortcut" to jump to "set_refresh" and return from there
__attribute__ ((noinline))
     void iWaitRecal ()		// if inlined, the JMP -> RTS goes astray!!!
{
   Vec_Loop_Count++;
   // I assume EVERYTHING is done with DP = D0
   // BSR DP_to_D0 ;DP to I/O
   asm ("jmp 0xF1A2");		// Set_Refresh
}

static volatile int8_t counter = 0;
static volatile int8_t counterDummy = 0;

unsigned int8_t mouse_x, mouse_y;
int8_t mouse_down, mouse_was_down;
volatile unsigned int8_t *rand = (volatile unsigned int *) 0xc87b;
volatile unsigned int8_t *timer_lo = (volatile unsigned int *) 0xD004;

__attribute__ ((interrupt))
static void gameLoop (void)
{
   // for anything except the t2 timer we want to rti immediately.
   if ((dp_VIA_int_flags & 0x20) == 0)
      return;

   iWaitRecal ();
   *(volatile int8_t *) 0xC81A = 0;	// maximum analog resolution
   Joy_Analog ();

   mouse_x = (uint8_t) (((long) Vec_Joy_1_X + 128L));	// -128:127 maps to
							// 0:255
   mouse_y = (uint8_t) (((long) Vec_Joy_1_Y + 128L));	// but scaled down to 
							// preserve margins

   Reset0Ref ();
   set_scale (DRAWING_SCALE);
   Intensity_7F ();

   // DRAW STUFF HERE

   Read_Btns ();
   mouse_down = ((Vec_Btn_State & 8) != 0);

   Reset0Ref ();
   set_scale (DRAWING_SCALE);
   Intensity_7F ();
   last_intensity = -128;
   if (mouse_down && !mouse_was_down) {
      // this was a click
   } else if (mouse_down) {
      // this is a continuing drag
   } else if (mouse_was_down) {	// (but is no longer...)
      // end of drag - drop now.
   } else {
      // no change, just redraw
   }
   mouse_was_down = mouse_down;

   // DRAW MORE STUFF HERE?

   dotmask = (dotmask << 1) | (dotmask >> 7);
}

#define IRQBASE 0xCBF8		// this must be IRQ not FIRQ!
uint16_t volatile *const IRQ = (uint16_t *) (IRQBASE + 1);
uint8_t volatile *const IRQ_INST = (uint8_t *) IRQBASE;

#define WAIT_VALUE 15

void start_graphics_thread (void (*gameLoop) (void))
{
   *IRQ_INST = (unsigned int) 0x7e;	// JMP ... this is actually code!,
					// first a JMP instruction
   *IRQ = (unsigned long) gameLoop;	// to Address

#define LITTLE_ENDIAN(a) ( (((a)>>8L)&255L) | (((a)&255L)<<8L) )

   Vec_Rfrsh = (unsigned long int) (LITTLE_ENDIAN (50000UL));

   // ensure timer is sensible to start with
   dp_VIA_t2 = Vec_Rfrsh;	// in RAM the BIOS default value of T2 =
				// 30000 cycles

   // enable T2 interrupt generation in VIA
   dp_VIA_int_enable |= 0x20;
   ENABLE_IRQ_6809;
}

int main (void)
{
   // unfortunately, on emulator at least, very first random is always the
   // same
   // maybe ask Malban to add some randomicity to initial hardware timer?
   initRandom (rand[0], rand[1], rand[2], *timer_lo);

   Vec_Joy_Mux_1_X = 1;		// enable analog joystick mode
   Vec_Joy_Mux_1_Y = 3;

   mouse_was_down = FALSE;
   mouse_down = FALSE;
   start_graphics_thread (gameLoop);
   for (;;) {
      // DO COMPUTATION HERE
      asm ("CWAI  #0xef");	// Wait for interrupt to happen
   }
   return 0;
   (void) drawline;
   (void) mystrdup;
   (void) mystrchr;
   (void) atoui;
   (void) random8;
}
