Sounds like you'll have to write the algorithm yourself. Take some time and think about it. If you run into road blocks come ask for help. I could just write the algorithm and give it to you, but...