Refactored and improved concatenation logic.