Fixed algorithm, works perfectly now. unsure of how well it will scale.