refactored and fixed a bug