Fixed logic issues and cleaned up code