Almost  complete rewrite

Now includes inline comment and tests for maintainability.