some code refactoring to get rid of code repetition and anonymous funtions