Cleaned up SQL queries; partial progress on templates.