Refactor and make more generic