almost working algo