Removed redundant code, and added extra checks.