some more refactor and bug fixes