Mostly working reworked loop, keeping for prosterity but will be replaced