transfer lots of changes from my fork of v0.3.8