Clean up code some

- Consolidate duplicated code
- Remove obsolete, dead code
- Add some more error and/or debug logging