Added code from @invalidname's original version.