some refactoring proposed by pavelpower