First refactoring - now works.  Needs cleaning up.