reduced number of loops to improve total runtime.