a little refactoring and optimization