That function is way too large. Dissect it into smaller functions. Create helper functions where possible.
Closes #5 (closed).