changing algorithm; some minor issues still