Bug fixes and code reformat