massive speedup + small tweaks for correct output