Clarified variables and corrected logic for valid function.