bug fixes and porting some codes to scala