Refactored and added some tests