#include <itk/raster.h>
#include <itk/bit_count.h>
#include <ocr/get_shape.h>


#ifndef DO_OCR_INLINE
#include <ocr/get_shape.h>
#endif


unsigned
get_shape( const Raster &raster
         , unsigned tl_x, unsigned tl_y
         , unsigned br_x, unsigned br_y)
{
  unsigned height = br_y - tl_y;
  unsigned width  = br_x - tl_x;
  unsigned line;
  unsigned i;
  unsigned j;
  unsigned ty;
  unsigned by;
  unsigned lx;
  unsigned rx;
  unsigned thresh = ((height * width) / 30) * 3 / 8;
  unsigned key = 0;
  unsigned bit = 0;

  for (i = 0; i < 6; ++i) {
    ty = tl_y + (height * i) / 6;
    by = tl_y + (height * (i + 1)) / 6;
    for (j = 0; j < 5; ++j) {
      int bits = 0;
      lx = tl_x + (width * j) / 5;
      rx = tl_x + (width * (j + 1)) / 5;
      for (line = ty; line < by; ++line) {
        bits += bit_count( raster[ line], lx, rx);
      }
      if (bits > thresh) {
        key |= (1 << bit);
      }
      ++bit;
    }
  }
  return key;
}
