Bug fixes, refactoring and new apis from master.