very smart algorithm leanred from discussion board.