Removed some duplication and improved logic