correct algorithm outlined in comments