restructured code

It should be a bit more readable now.