Separate output serialization to its own method and flush stream.

Also moved regexp creation outside of interpreter loop