improve memory allocation

use realloc to seemingly solve errors in men allocation
arrange uniform init and fini block in worker thread
break match function into 3 parts