Bug Fix: change the order of for-loop