Enqueue threads in right order and fix submatches

Threads are enqueued in a FIFO queue, so that higher priority threads
are executed first.

Submatches and nested submatches are now correctly handled.