//  DescriptionHere - buildPatterns.cpp
//  Created by John Ryland (jryland@xiaofrog.com), 03/11/2017
//  Copyright (c) 2017 InvertedLogic
//  All rights reserved.
#include <stdio.h>
#include <stdint.h>
#include <string.h>

const int width = 5;
const int height = 5;

int main(int argc, char *argv[])
{
  const char* fileName = "tools/patterns.txt";
  FILE* f = fopen(fileName, "r");
  if (!f) {
    printf("error opening file: %s\n", fileName);
    return -1;
  }
  char buf[256];
  uint8_t pattern[width][height];
  int patternLine = 0;
  memset(pattern, 0, sizeof(pattern));
  int patternIndex = 0;
  printf("id int primary key, tiles int, score int, position int, length int\n");
  while (fgets(buf, 255, f))
  {
    if (strncmp(buf,"---",3) == 0) {  // any line in the input starting with '---' is a deliminator
      int tiles = 0;
      uint8_t pos1[width] = { 0, 0, 0, 0, 0 };
      uint8_t len1[width] = { 0, 0, 0, 0, 0 };
      for (int i = 0; i < width; i++)
        for (int j = 0; j < height; j++)
          if (pattern[j][i] && ++tiles && ++len1[i] && len1[i]==1)
            pos1[i] = j;
      uint64_t pos = 0, len = 0;
      for (int i = 0; i < width; i++) {
        pos <<= 8;
        len <<= 8;
        pos |= pos1[i];
        len |= len1[i];
      }
      int scores[8] = { 0, 0, 10, 25, 50, 100, 200, 500 }; // perhaps a seperate table in the DB for this
      int score = scores[tiles];
      // sqlite can handle int64_t, but not uint64_t - we don't need comparisons so we can just cast back and forth
      printf("%i, %i, %i, %lli, %lli\n", patternIndex, tiles, score, pos, len); // pos and len are signed for sqlite compatibility
      patternIndex++;
      memset(pattern, 0, sizeof(pattern));
      patternLine = 0;
    } else {
      for (int i = 0; buf[i] && i < width; i++)
        if (buf[i] == 'X')
          pattern[patternLine][i] = 1;
      patternLine++;
      if (patternLine > height) { // Error
        printf("expecting a deliminator in input\n");
        return -1;
      }
    }
  }
  return 0;
}

