some rearrangements in main for clarity