Porting some code from 1.x client, refactoring