Shuffle implementation and some refactoring