Refactor append function