Refactor and fix border generation