A lot of these variables seem spread out all over the place. This file could use some more functions that split up the work, and variables should be declared up front to make it easier to find them.