refactor and test for random working