code refactor and bugfix