Refactoring

A bit of refactoring to this mess.