refactor and bugfix.