Untested final code.

All logic and rules were implemented and tested briefly for basic
conditions. More thorough testing of all cases is required.