Few bug fixes and cleaned up code