maybe pull out some of this stuff in to functions? the comments are probably a clue which things should be refactored..