master is subtly incorrect, but so is this
complete rewrite, stealing a lot of ideas from pipes.