Review by @Shougo, some refactorings