More code cleanup, defensive coding, and method extraction.