Refactor nesting and remove duplicate code