Best working algo so far