final working code with fix to shuffle and sort