Fixed logic issue and added check