Tweaks to middleware processing

Also some small code house keeping