pattern match algorithm