some performance improvement + code refactoring