#!/usr/bin/env ruby
#

require 'erb'

$outfile = nil
$outfile_index = 0
$header_text = File.read("header.txt")

def close_file
	$outfile.puts "</pre></body></html>"
	$outfile.close
end

def open_new_file
	if $outfile != nil
		close_file
	end

	filename = sprintf("index%03i.html", $outfile_index)

	$outfile = File.open(filename, "w")

	$outfile.puts "<html><body>"
	$outfile.puts $header_text
	$outfile.puts "<pre>"

	$outfile_index += 1
end

def h(s)
	ERB::Util.html_escape(s)
end

open_new_file

lines = 0

File.open("competn-index.txt") do |file|
	file.each_line do |s|
		s = s.chomp

		if s =~ /^Archive:\s*(\S+)/
			path = $1.sub(/^\.\//, "")

			if lines > 300
				open_new_file
				lines = 0
			end
			case path
			when /^pub\/compet-n\/(.*)/
				url = "http://archive.org/download/competn/competn.zip/" + $1
			when /^pub\/sda\/(.*)/
				url = "http://archive.org/download/competn/sda.zip/" + $1
			else
				raise Exception("Unknown path #{path}")
			end
			s = "Archive: <a href=\"#{url}\">#{path}</a>"
		else
			s = h(s)
		end

		$outfile.puts s
		lines += 1
	end
end

close_file

