#include <stdio.h>
#include "graph.h"
#include "riverpic.h"
#include "defs.h"
#include "graph.h"

#include "../pic/river01.xpm"
#include "../pic/river02.xpm"
#include "../pic/river03.xpm"
#include "../pic/river12.xpm"
#include "../pic/river13.xpm"
#include "../pic/river23.xpm"

#include "../pic/river012.xpm"
#include "../pic/river013.xpm"
#include "../pic/river023.xpm"
#include "../pic/river123.xpm"

#include "../pic/river4.xpm"

#include "../pic/river0.xpm"
#include "../pic/river1.xpm"
#include "../pic/river2.xpm"
#include "../pic/river3.xpm"

static char **corners2[] = {
  river01_xpm,
  river02_xpm,
  river03_xpm,
  river12_xpm,
  river13_xpm,
  river23_xpm };

static char **corners3[] = {
  river012_xpm,
  river013_xpm,
  river023_xpm,
  river123_xpm };

static char **start[] = {
  river0_xpm,
  river1_xpm,
  river2_xpm,
  river3_xpm };

// encoding to send map to other players
static char **encoding[] = {
  NULL,
  river0_xpm,
  river1_xpm,
  river2_xpm,
  river3_xpm,
  river012_xpm,
  river013_xpm,
  river023_xpm,
  river123_xpm,
  river01_xpm,
  river02_xpm,
  river03_xpm,
  river12_xpm,
  river13_xpm,
  river23_xpm,
  river0123_xpm };

static long compiledRivers[] = {
  0, 0, 0, 0,
  0, 0, 0, 0,
  0, 0, 0, 0,
  0, 0, 0, 0
  };

inline void Swap(int &a, int &b) { int temp = a; a = b; b = temp; }

// return the correct river bitmap for just two points
char **WhichRiverBitmap2(int a, int b)
{
  static int table[] = { 0, 3, 5 };
  if (a > b) Swap(a, b);
  return corners2[table[a]+b-a-1];
}

// same for 3 point intersection
char **WhichRiverBitmap3(int a, int b, int c)
{
  if (a > b) Swap(a, b);
  if (b > c) Swap(b, c);
  if (a > b) Swap(a, b);
  if (b == 1) return corners3[c-2];
  else return corners3[2+a];
}

// use this to compute the river bitmap which is passed to
// draw river
char **WhichRiverBitmap(int numPoints, int a, int b, int c)
{
  if (numPoints == 1) return start[a];
  else if (numPoints == 2) return WhichRiverBitmap2(a, b);
  else if (numPoints == 3) return WhichRiverBitmap3(a, b, c);
  else return river0123_xpm;
}

void DrawRiver(int x, int y, int riverPic)
{
  if (compiledRivers[riverPic] == 0)
    compiledRivers[riverPic] = screen->CompilePixmap(encoding[riverPic]);
  screen->DrawPixmap(x, y, compiledRivers[riverPic]);
}

int EncodeRiverBitmap(char **bitmap)
{
  char ***ptr = encoding;
  while (bitmap != *ptr) ++ptr;
  return ptr-encoding;
}

char **DecodeRiverBitmap(int n)
{
  return encoding[n];
}
