I had not upvoted your comment because I was testing your code. I ran some fixed value tests and some random tests. Looks like your code is taking care of all the scenarios :)
Upvoted your answer with 100%. Unless I get a better solution, looks like you are going to be the winner of this Gig.
Glad it worked. I had fun solving it.