fixed bugs

I have fixed some bugs and done some code clean up. Also it should work now when you test my changes before merging