Fix potential bug and clean up code