module main

import (
  std.io
  std.os
  std.alloc

  mdhtml
)

let close_input(input: *mut dyn std.io.Reader) {
  let mut file_reader, ok = input.(std.io.FileReader)
  if ok {
    file_reader.close()
  }
}

let main() {
  let mut input_file = "-"
  if @len(std.os.args) == 2 {
    input_file = std.os.args[1]
  } else if @len(std.os.args) > 2 {
    std.io.eprintln("Usage: render [input_file.md]")
    std.os.exit(1)
  }

  let input: *mut dyn std.io.Reader = if input_file.eq("-") {
    std.io.stdin.&mut
  } else {
    let mut got = std.io.FileReader.open(input_file)
    if got.is_err() {
      std.io.eprintln("Error opening file {}: {}", input_file, got.unwrap_err().message())
      std.os.exit(1)
    }
    let mut reader = got.unwrap()
    reader.&mut
  }
  defer close_input(input)

  let output: *mut dyn std.io.Writer = std.io.stdout.&mut

  if !mdhtml.md_to_html(input, output) {
    std.io.eprintln("Error converting markdown to HTML")
    std.os.exit(1)
  }
}