Fixed bugs, cleaned up the code