got rid of duplicated code, put into function