Working version of pattern recognition with bugfixes in place