Mess of code, functioning just about right.