Bug fixes and refractoring