small bug fixes and refactor