Restructured code

Put things into functions