Fix several logic errors