Bug fixes and simplify code