Changed to recursive algorithm