Heavy refactoring. Test cases still to be completed