This code *has* to get rewritten at some point.  It's too complicated, should be split into function, needs error handling, etc, etc.