Please put all of this (from line 495 to 531) in a proc. It makes it a huge pain to read.