refactored code folding so it handles all cases now