fixed a some smallish bugs and cleaned up the code