Refactoring - reorganized code a bit for clarity.