reoragnized so that main function is simpler