Some refactoring. Needs lots of work