Various fixes/improvements, taking into accoutn wkeese's feedback
(cherry picked from commit e9668a9d78666189add8a191d680fa3b4c8dac9f)