Cleaned up code a bit for the main logic.
Updated.