if ENV['COVERAGE'] == "1"

  require 'simplecov-rcov'
  class SimpleCov::Formatter::MergedFormatter
    def format(result)
       SimpleCov::Formatter::HTMLFormatter.new.format(result)
       SimpleCov::Formatter::RcovFormatter.new.format(result)
    end
  end

  SimpleCov.formatter = SimpleCov::Formatter::MergedFormatter

  SimpleCov.start :rails do
    # remove the :root_filter so that we can see coverage of external dependencies (i.e., jam_ruby)
    filters.clear

    # ignore Ruby itself (...not to be confused with jam_ruby)
    add_filter "/lib/ruby/"

    # ignore Rails subfolders which don't contain app code
    %w{config coverage db doc features log script spec test tmp}.each do |dir|
      add_filter "#{dir}/"
    end

    # ignore all gem code except our jam gems
    add_filter {|src| src.filename =~ /ruby.*\/gems\// unless src.filename =~ /\/gems\/jam/ }

    # categorize JamRuby in the coverage report:
    add_group 'Jam Ruby', 'jam_ruby'
  end

  all_files = Dir['**/*.rb']
  base_result = {}
  all_files.each do |file|
    absolute = File::expand_path(file)
    lines = File.readlines(absolute, :encoding => 'UTF-8')
    base_result[absolute] = lines.map do |l|
      l.encode!('UTF-16', 'UTF-8', :invalid => :replace, :replace => '')
      l.encode!('UTF-8', 'UTF-16')
      l.strip!
      l.empty? || l =~ /^end$/ || l[0] == '#' ? nil : 0
    end
  end

  SimpleCov.at_exit do
    coverage_result = Coverage.result
    covered_files = coverage_result.keys
    covered_files.each do |covered_file|
      base_result.delete(covered_file)
    end
    merged = SimpleCov::Result.new(coverage_result).original_result.merge_resultset(base_result)
    result = SimpleCov::Result.new(merged)
    result.format!
  end

end
