Some explanation of what all this stuff is for would be helpful ... either through a comment or by refactoring this into separate well-named functions?