Dividing complexity into files
Refactoring to make it clean: no more sql inside the hooks