this block of code needs some rework, could you please refactor and add comments