Refactor a bit
Implement middleware for 4.1

Fixes #1