Fix very subtle bugs in output dequeuing (unfortunately, I haven't managed to design a test case to reproduce it!)
Changes from dselassi's code review (on github), thanks! Also added performance test