#!/usr/bin/ruby
#
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "gem/gems/kramdown-0.14.1/lib"))
require 'kramdown'

class ::String
  ##
  ## Discard invalid characters and output a UTF-8 String
  ##
  ## @return     [String] UTF-8 encoded string
  ##
  def utf8
    encode('utf-16', invalid: :replace).encode('utf-8')
  end

  ##
  ## Destructive version of #utf8
  ##
  ## @return     [String] UTF-8 encoded string, in place
  ##
  def utf8!
    replace utf8
  end

  def punctuation_to_markdown
    force_encoding("utf-8")
    .gsub(/[“”]/, '"')
    .gsub(/[‘’]/, "'")
    .gsub(/[—–]/, "--")
    .gsub(/[…]/, "...")
  end
end

input = STDIN.read.punctuation_to_markdown.utf8
# input =<<EOF
# C> This is a centered sentence.
# C> Another centered sentence, in the same paragraph as sentence one.
# C>
# C> This sentence will be in a new paragraph.

# * one
# * two
# * three
#   * three.one
#   * three.two


# > **This is a blockquote**
# >
# > A blockquote should be indented.
# >
# > The second paragraph should be indented as well.
# >
# > And the third!
# >
# > > You can also have blockquotes in blockquotes

# A> This is an aside.
# A>
# A> This is also sometimes known as a sidebar.
# A>
# A> To make one of these, put `A>` at the beginning of the lines of
# A> the aside, similar to the `>` that you use for a blockquote.

# EOF
in_quote = false
output = []
# input += "\n\n&nbsp;"
input.split(/\n/).each do |line|
  if line =~ /^([CAWTEIQDX])>/
    # output.push(%Q{<blockquote class="leanpub-#{$1}">}) unless in_quote
    in_quote = $1
  else
    output.push("{: .lp-#{in_quote} }\n\n") if in_quote
    in_quote = false
  end

  if in_quote
    output.push(line.gsub(/^[CAWTEIQDX]> */,'> '))
  else
    output.push(line)
  end
end

# puts output.join("\n")
puts Kramdown::Document.new(output.join("\n").strip).to_html
