Working version; refactored functions heavily.  Some bugs remain.