Fix bug and improved code