Old version (parts due to @maximillianh) checked in for completeness.