Simplify some code logic and correct bugs