Refactor and add some missing functions