Reorganizing the code

It's probably better to review per commit.