#!/usr/bin/ruby

require 'cgi'

Consonant = 'bcdfghjklmnpqrstvwxz'
Vowel = 'aeoiuy'
Data = File.join(File.dirname(__FILE__), 'weosr-data')

Table = [
	[/ld/, 'yld'],
	['b', 'v'],
	['orse', 'eosr'],
	[/(.)re/, 'yr\1e'],
	[/a([eiou])/, '\1a'],
	[/([#{Consonant}])i([#{Consonant}])/, '\1y\2'],
	['oe', 'yoe'],
	['ck', 'cy'],
	[/([#{Consonant}])e([#{Consonant}])/, '\1\2ey'],
	['ty', 'yt'],
	['the', 'teh'],
	['ite', 'yte'],
	['ng', 'nge'],
	['aid', 'edde']
]

def trans(s)
	Table.each { |i, o| s = s.gsub(i, o) }
	if(s and !s.empty? and s != 'couyld ve weosr')
		File.open(Data, 'a') { |f|
			f.puts(s)
		}
	end
	s
end

cgi = CGI.new('html4')

o = ''

if cgi.params['phrase']
	cgi.params['phrase'].each { |e|
		o << trans(e)
	}
end

cgi.out {
	cgi.html {
		cgi.head {
			%{
				<title>Ye Olyde Englyseh yTpo</title>
				<style type='text/css'>
					body { font-family: "Celestia Antiqua", "Bookman Antigua", "Centaur", "Serif"; font-weight: normal; margin-left: 10em; margin-right: 10em; margin-top: 4em; margin-bottom: 10em; color: #000; background-color: #fff; }
					h1, h2 { text-align: center; font-weight: normal; margin: 12pt; }
					h1 { font-size: 72pt; }
					h2 { font-size: 44pt; }
					p { margin: 0; }
					form { text-align: center; }
					input[type='text'] { font-family: inherit; font-size: 18pt; background-color: #eeb; }
				</style>
			}
		} + 
		cgi.body {
			cgi.h1 { 'Ye Olyde Englyseh yTpo' } +
			cgi.h2 { 'Couyld ve weosr' } +
			cgi.form { 
				cgi.text_field('phrase') + 
				cgi.submit("Make it weosr")
			} +
			cgi.p { o } + File.readlines(Data).reverse[1..10].map { |e| cgi.p { e } }.join('')
		}
	}
}
