refactoring and bug fixing, still some problems