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

#include "global.h"
#include "graph.h"
#include "display.h"
#include "pixmaps.h"

static CPixmap *corners2[] = {
  &river01_pic,
  &river02_pic,
  &river03_pic,
  &river12_pic,
  &river13_pic,
  &river23_pic };

static CPixmap *corners3[] = {
  &river012_pic,
  &river013_pic,
  &river023_pic,
  &river123_pic };

static CPixmap *start[] = {
  &river0_pic,
  &river1_pic,
  &river2_pic,
  &river3_pic };

// encoding to send map to other players
static CPixmap *encoding[] = {
  NULL,
  &river0_pic,
  &river1_pic,
  &river2_pic,
  &river3_pic,
  &river012_pic,
  &river013_pic,
  &river023_pic,
  &river123_pic,
  &river01_pic,
  &river02_pic,
  &river03_pic,
  &river12_pic,
  &river13_pic,
  &river23_pic,
  &river0123_pic };

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

// return the correct river bitmap for just two points
CPixmap *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
CPixmap *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
CPixmap *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_pic;
}

void DrawRiver(WDisplay *window, MapCoord c, int riverPic)
{
  window->DrawPixmap(c, encoding[riverPic]);
}

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

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