refactor and fix bug #2