More bug fixing and refactoring

The basic features seem to be working now. More work and testing ahead.