main outer loop