New algorithm for the main funtion. will be mucg faster when it's all figured out