Porting bug fixes and some changes

Porting some bug fixes and changes that I have done in my Fork from version 1.4.2.386.