Some refactoring. Still need to write tests