Large clean up of middleware, collected in one file. And other improvements as well.