Cleaned up a little; still a bloody mess though. Embarrassing for a professional programmer!