Add pl argument to all segments

Argument holds state and is also responsible for logging.

Fixes #340 and superceeds #330.

Is based on threaded-3 branch (meaning that proper merge is merge threaded-3, rebase, merge this).