refactored and cleaned up a bit