Fixing issues found during code review

- eliminating duplicate code
- implementing missing functionality
- cleanup
- minor other refactorings
- now uses -Xlint:unchecked to detect improper casts/conversions
- fixing issues found by lint where possible, added SuppressWarnings("unchecked") where not possible
- some more work on existing test cases, see #1