move pattern detection to separate function