#!/System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/ruby
# encoding: utf-8

# Usage: `cat mydocument.md|./avoidwords.rb > output.html`

$input = STDIN.read

avoid_words = ['mkavoid',ARGV[0].split("\n").map {|line|
  line.strip
}.delete_if { |line| line =~ /^(\s*|^\/\/.*?)$/ }.uniq]

alt_words = ['mkalt',ARGV[1].split("\n").map {|line|
  line.strip
}.delete_if { |line| line =~ /^(\s*|^\/\/.*?)$/ }.uniq]

highlight_words = ['mkhighlight',ARGV[2].split("\n").map {|line|
  line.strip
}.delete_if { |line| line =~ /^(\s*|^\/\/.*?)$/ }.uniq]

temp_words = ARGV[3].nil? ? false : ['mktemp',ARGV[3].split("\n").map {|line|
  line.strip
}.delete_if { |line| line =~ /^(\s*|^\/\/.*?)$/ }.uniq]

exit if avoid_words.nil?

def e_sh(str)
  str.to_s.gsub(/(?=[^a-zA-Z0-9_.\/\-\x7F-\xFF\n])/, '\\').gsub(/\n/, "'\n'").sub(/^$/, "''")
end

# filename = '~/Desktop/avoidwords.txt'
# avoidwords = []

# compiled = ""
# File.open(File.expand_path(filename),'r') do |line|
# 	compiled += line.read
# end

def split_headers(input)
	headers = []
	body = []
	lines = input.split("\n")
	in_headers = false
	lines.each_with_index {|line,i|
		if line =~ /^[a-z]{1,13}( [a-z0-9]{1,13}){0,4}:\s+.+$/i
			headers.push(line)
			in_headers = true
		elsif line =~ /^\s*$/
			body = lines[i..lines.length]
			return [headers.join("\n"),body.join("\n")]
		elsif in_headers == false
			body = lines
			return [headers.join("\n"),body.join("\n")]
		end
	}

end

def highlight(the_class,word_array,body)
  phrases = {}
  phrases[the_class] = []

  word_array.each {|word|
    next if word =~ /^\s*$/
    phrases[the_class].push(word)
  }

  phrases.each {|k,v|
    type = k
    v.each {|phrase|
      parts = phrase.split(" ")
      bad_words = false
      %w{span class avoidword mkavoid mkalt mktemp mkhighlight}.each {|bad_word|
      	bad_words = true if parts.include? bad_word
      }
      next if bad_words
      if parts.length > 1
        regex = /\b(?![^<]*?>)(\[?#{parts.join('(?:[\*_\+\-\[\]\(\) ]*|\][\[\(].*?[\]\)]\s*)?')}(?:\][\[\(].*?[\]\)]|))\b/i
      else
        regex = /\b(?![^<]*?>)(#{phrase})\b/i
      end
      body.gsub!(regex,"<span class=\"avoidword #{type}\">\\1</span>")
    }
  }
  return body
end

headers, body = split_headers($input)

body = highlight(temp_words[0],temp_words[1],body) if temp_words

[avoid_words,alt_words,highlight_words].each {|this_class,this_array|
	body = highlight(this_class,this_array,body)
}

puts headers + "\n" + body
