refactored into separated methods so that the code can be used as library