I think I know what you're doing here, but it's really hard to read. If you could put this in well named sub methods or pack everything into an object even someone not a coder would be able to understand what you're doing