This entire code is going to be refactored soon as part of the new search UI work. I know it's ugly (it was, after all, some of the very first Python I wrote), but I wouldn't worry about it now, so long as it works.