fix error when middleware not declared as last

Also better documentation and identation