%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                        %
%                               CCSDS_Int                                %
%                                                                        %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%ZABEZPECUJE INTERLEAVNUTIE A DEINTERLEAVNUTIE DAT
%Vstupne premenne:
%data - ktore budu de/interleavnute [double,int]
%x - oznacuje interleaver/deinterleaver [bool][1-int,0-deint]
%Vystupna premenna:
%out - interleavnute/deinterleavnute data [double,int]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function out = CCSDS_Int(data,x)

inf = 9e9;
[a, b] = size(data);
table = [1784 8 223;3568 8 446;7136 8 892;8920 8 1115];                     %hodnoty pre jednotlive velkosti bloky
vys_int = repmat(inf, [a, b]);
vys_dei = repmat(inf, [a, b]);
[r, s] = find(table(:,1)==b);

if (~isempty(a)&&~isempty(b))
    %%INTERLEAVER
    if (x==1)
        for s=1:b
            m = mod((s-1),2);                                               %vypocet podla standardu CCSDS
            i = floor(((s-1)/(2*table(r,3))));
            j = (floor((s-1)/2))-(i*table(r,3));
        	t = mod(((19*i)+1),4);
            q = mod(t,8)+1;
            c = mod(((31*j)+(21*m)),table(r,3));
            in = 2*(t+(c*4)+1)-m;
            vys_int(a, in) = data(a, s);
        end
        out = vys_int;

    %%DEINTERLEAVER
    elseif (x==0)
        for s=1:b
            m = mod((s-1),2);                                               %vypocet podla standardu CCSDS
            i = floor(((s-1)/(2*table(r,3))));
            j = (floor((s-1)/2))-(i*table(r,3));
            t = mod(((19*i)+1),4);
            q = mod(t,8)+1;
            c = mod(((31*j)+(21*m)),table(r,3));
            in = 2*(t+(c*4)+1)-m;
            vys_dei(a, s) = data(a, in);
        end
        out = vys_dei;
    end
else
    error('CHYBA');
end
end