Initial patch, reviewed by Chris Conlon. Work in progress.