Fought it, but need to organize this code in a more sensible way