Fix error handling and clean up code

Fix indentation
Move processing into a function
Change control flow slightly (use continue)