Refactored Shiandow's patch to reduce code duplicates.