comments added and reordering logic corrected.