Bug fixes and refactoring

Change-Id: If9c46fe3b095b2844c8cb94556853154455ca23a