Refactor and add type signatures