refactor and add debugging