Massively overhauled my code, so hopefully this works now.