Fix error handling and clean up code

Fix indentation
Move processing into a function
Change control flow slightly (use continue)
Merge pull request #1 from porglezomp/master

Fix error handling and clean up code.