refactor and bunch of bugfix