First working pass. Code is still pretty hack 'n' slashy, but it appears to work.