almost working algorithm. Test cases are now needed