Some fixes requested by @waylan, cleanup and tests improvements