fixed a few small bugs and refactored a bit