Third algorithm works now