#!/usr/pkg/bin/ruby40
require 'yaml'
require 'kramdown-rfc2629'
require 'kramdown-rfc/parameterset'
require 'kramdown-rfc/refxml'
require 'kramdown-rfc/doi'

# doilit -c 10.6028/NIST.SP.800-183 10.1016/j.adhoc.2015.04.007 10.1109/MIC.2012.29 10.1145/2507924.2507954

$verbose = false
$fuzzy = false
$handle = "a"
$xml = false
$site = "https://dx.doi.org"
$global_markdown_options ||= {} # work around uninitialized

litent = {}
ARGV.each do |doi|
  case doi
  when "-c"
    begin
      require 'open-uri/cached'
    rescue LoadError
      warn '*** please "gem install open-uri-cached" to enable caching'
    end
    next
  when "-f"
    $fuzzy = true
    next
  when "-v"
    $verbose = true
    next
  when /\A-s=(.*)/
    $site = $1
    next
  when /\A-h=(.*)/
    $handle = $1
    next
  when /\A-x=(.*)/
    $handle = $1
    $xml = true                 # make all come out as XML
    next
  when /\A-/
    warn "*** Usage: doilit [-c] [-f] [-v] [-h=handle|-x=xmlhandle] doi..."
    exit 1
  end

  lit = doi_fetch_and_convert(doi, fuzzy: $fuzzy, verbose: $verbose, site: $site)

  while litent[$handle]
    $handle.succ!
  end
  litent[$handle] = lit
end
if $xml
  litent.each do |k, v|
    puts KramdownRFC::ref_to_xml(k, v)
  end
else
  # 1.9 compat: s/lines/each_line.to_a/
  puts litent.to_yaml.gsub(/^/, "  ").each_line.to_a[1..-1]
end
