code refactored and bug fixed