Fixed memory leak in stream engine

Pieter's fix, without the odd extra commits.