function zigzag = EQA3YM_zigzag( quant )
% Reorder the quantized elements to have long runs of zero-valued coeff

[X, Y, ~] = size(quant);
block_size = 8;
block_rows = floor(X/block_size);
block_cols = floor(Y/block_size);

% Generating index matrix for rearrangement
idxs = reshape(1:block_size*block_size, [block_size block_size]);
idxs = fliplr(spdiags(fliplr(idxs)));
idxs(:,1:2:end) = flipud(idxs(:,1:2:end));
idxs(idxs==0) = [];

% Reorder blocks one by one
zigzag = zeros(64, block_rows*block_cols,3);
for c = 1:3
    for i = 1:block_rows
        for j = 1:block_cols
            temp = quant((i-1)*block_size+1:i*block_size, (j-1)*block_size+1:j*block_size, c);
            zigzag(:,(i-1)*block_cols+j,c) = temp(idxs);
        end
    end
end

% Vectorize matrix
zigzag = zigzag(:);

end

