Fixed algorithm to match all possible cases