refactored and bugs removed