Various bug fixes and improvement