Moved some code blocks into functions to (hopefully) make reader and writer more readable.