#include <iostream.h>
#include <itk/raster.h>
#include <itk/bit_count.h>
#include <ocr/find_lines.h>

#ifndef DO_OCR_INLINE
#include <ocr/find_lines.inl>
#endif


Line_Def::Line_Def()
: m_start_line( 0)
, m_end_line( 0)
{
}


Line_Def::Line_Def( unsigned new_start_line, unsigned new_end_line)
: m_start_line( new_start_line)
, m_end_line  ( new_end_line  )
{
}


Find_Lines::Find_Lines( unsigned new_min_line_size)
: m_min_line_size( new_min_line_size)
, m_max_lines( 0)
, m_line_defs( 0)
, m_num_lines( 0)
, m_black_threshold( 0)
{
}


Find_Lines::~Find_Lines()
{
  delete []m_line_defs;
}


bool
Find_Lines::find_lines( const Raster &raster)
{
  if (!m_min_line_size) {
    assert( m_min_line_size);
    return false;
  }

  unsigned max_lines = (raster.height() / min_line_size());
  if (max_lines > m_max_lines) {
    delete []m_line_defs;
    m_line_defs = new Line_Def[ max_lines];
    m_max_lines = max_lines;
  }
  m_num_lines = 0;

  unsigned i = 0;
  unsigned bc;
  unsigned lines = 0;
  unsigned sline;
  unsigned eline;
  while (i < raster.height()) {
    lines = 0;
    bc = bit_count( raster[ i], raster.width());
    while ((i < raster.height()) &&
           (bc >= black_threshold() || lines && (lines < min_line_size()))) {
      if (!lines) {
        sline = i;
      }
      eline = i;
      ++i;
      ++lines;
      bc = bit_count( raster[ i], raster.width());
    }
    if (lines >= min_line_size()) {
      m_line_defs[ m_num_lines].set_start_end( sline, eline);
      ++m_num_lines;
    }
    ++i;
  }
  return true;
}
