Really very - VERY messy code now, but function is running according to expectations