Fixing some bugs and cleaning some code