///|
#derive(Debug)
pub suberror OcrError {
  InvalidImage(String)
  InvalidTemplate(String)
}

///|
pub extend OcrError with @debug.Debug::{to_repr}

///|
#derive(ToJson)
pub struct Box {
  left : Int32
  top : Int32
  right : Int32
  bottom : Int32
}

///|
pub extend Box with ToJson::{to_json}

///|
pub fn Box::new(
  left : Int32,
  top : Int32,
  right : Int32,
  bottom : Int32,
) -> Box {
  { left, top, right, bottom, }
}

///|
pub struct Image {
  width : Int32
  height : Int32
  priv ink : Array[Bool]
}

///|
/// Parse a plain PBM image (P1), including Netpbm comments.
pub fn Image::from_pbm(text : String) -> Image raise OcrError {
  let chars = text.iter()
  if header_token(chars) != "P1" {
    raise InvalidImage("expected a plain PBM image with a P1 header")
  }
  let width = parse_dimension(header_token(chars))
  let height = parse_dimension(header_token(chars))
  if width <= 0 || height <= 0 || width > 16_000_000 / height {
    raise InvalidImage("invalid image dimensions")
  }
  let size = width * height
  let ink = Array(capacity=size)
  while chars.next() is Some(ch) {
    if ch == '#' {
      skip_comment(chars)
    } else if !pbm_whitespace(ch) {
      if ink.length() == size || (ch != '0' && ch != '1') {
        raise InvalidImage("invalid bitmap data")
      }
      ink.push(ch == '1')
    }
  }
  if ink.length() != size {
    raise InvalidImage("truncated bitmap data")
  }
  { width, height, ink, }
}

///|
fn pbm_whitespace(ch : Char) -> Bool {
  ch == ' ' || (ch.to_int() >= 9 && ch.to_int() <= 13)
}

///|
fn skip_comment(chars : Iter[Char]) -> Unit {
  while chars.next() is Some(ch) {
    if ch == '\r' || ch == '\n' {
      break
    }
  }
}

///|
fn header_token(chars : Iter[Char]) -> String raise OcrError {
  let token = StringBuilder()
  let mut length = 0
  while chars.next() is Some(ch) {
    if ch == '#' || pbm_whitespace(ch) {
      if ch == '#' {
        skip_comment(chars)
      }
      if length > 0 {
        break
      }
    } else {
      if length == 32 {
        raise InvalidImage("invalid PBM header")
      }
      token.write_char(ch)
      length += 1
    }
  }
  token.to_string()
}

///|
fn parse_dimension(text : String) -> Int32 raise OcrError {
  let mut value = 0
  for ch in text {
    if ch < '0' || ch > '9' || value > 1_600_000 {
      raise InvalidImage("invalid image dimensions")
    }
    value = value * 10 + ch.to_int() - '0'.to_int()
  }
  value
}

///|
fn Image::pixel(self : Image, x : Int32, y : Int32) -> Bool {
  self.ink[y * self.width + x]
}

///|
fn Image::row_span(
  self : Image,
  y : Int32,
  left : Int32,
  right : Int32,
) -> Bool {
  for x in left.. Bool {
  for y in top..