Code

Inluding tuned version of patch from #808