Restructured main loop BC sorting + creating output