Refactored and debuggedish