Started big overhaul due to faulty understanding of algorithm