Re-arrange code, prepare for multiprocessing (2)