Clean up main logic for wrapping

clean up main codes by identifying and collapsing common areas, removing redundant loops