#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <ctype.h>

typedef uint32_t UINT32;
typedef int32_t SINT32;
typedef uint16_t UINT16;
typedef int16_t SINT16;
typedef uint8_t UINT8;
typedef int8_t SINT8;

UINT8 memory[0x10000], *memory_DP = &memory[0xD000];

// Modify this header to suit your target...
SINT32 res, A, B, D, C;
UINT16 PC, X, Y, S, U, Z, DP, arg, ea, val;
UINT8 E, F, I, N, H, V, CC, msn, lsn;

#undef  JUMP
#define JUMP continue

#define simplify_flags() do { N = (((SINT8)N < 0)?1:0);     \
                              V = (((SINT8)V < 0)?1:0);     \
                              Z = ((Z == 0)?1:0);           \
                              C = ((C != 0)?1:0);           \
                              H = (((H & 0x10) != 0)?1:0);  \
                         } while (0)
#define restore_flags() do { N = (N ? 0x80:0);    \
                             V = (V ? 0x80:0);    \
                             Z = (Z ? 0 : 1);     \
                             C = (C ? 0x100 : 0); \
                             H = (H ? 0x10 : 0);  \
                           } while (0)
  

void mon(char *s) {
  printf("A=%02x B=%02x X=%04x Y=%04x S=%04x U=%04x CC=%02x DP=%02x E%cF%cH%cI%cC%cZ%cV%cN%c   %s", A, B, X, Y, S, U, CC, (UINT8)(DP>>8), E+'0', F+'0', (((H & 0x10) != 0)?1:0)+'0', I+'0', (((C & 0x100) != 0)?1:0)+'0', ((Z != 0)?1:0)+'0', (((SINT8)V < 0)?1:0)+'0', (((SINT8)N < 0)?1:0)+'0', s);
}

int main (int argc, char **argv) {
  FILE *bin = fopen ("polar_rescue.bin", "rb");
  if (bin == NULL) {
    fprintf(stderr, "Polar: cannot open polar_rescue.bin\n");
    exit(1);
  }
  X = 0x0000;
  for (;;) {
    A = fgetc (bin);
    if (A == EOF)
      break;
    memory[X++] = A;
  }
  fclose(bin);
  
  PC = 0x001F; S = 0xC000; A = B = X = Y = U = 0;
  CC = E = F = H = I = C = Z = V = N = 0;
  DP = 0; memory_DP = memory;
  
  for (;;) {
    switch (PC) {
#include "polar_rescue.c"
    default:
      if (PC >= 0x8000) {
        PC = memory[S++]<<8;
        PC |= memory[S++];
        JUMP;
      } else {
        fprintf (stderr, "Unknown jump to %04x\n", PC); exit(0);
      }
    }
  }
}