Refactor and fix reported problems