#include "eq_interleaver.h"

EQ_Interleaver::EQ_Interleaver()
{
}

vec EQ_Interleaver::interleave(vec a, vec b, vec c, bool tail)
{
    vec b_tails = b.right(3);
    vec c_tails = c.right(3);
    ivec index = to_ivec(linspace(a.length()-1,0,a.length()));
    b = b(index);
    c = c(index);

    vec d= concat(a,b.left(a.length()),c.left(a.length()));

    ivec odd_interleaver = to_ivec(linspace(0,d.length()/2-1,d.length()/2)*2);
    ivec even_interleaver = to_ivec(linspace(0,d.length()/2-1,d.length()/2)*2+1);
    Sequence_Interleaver<int> component_interleaver(odd_interleaver.length());
    component_interleaver.randomize_interleaver_sequence();
    odd_interleaver = component_interleaver.interleave(odd_interleaver);
    component_interleaver.randomize_interleaver_sequence();
    even_interleaver = component_interleaver.interleave(even_interleaver);

    interleaver_index = concat(odd_interleaver, even_interleaver);

    for (int i=0; i<d.length()/2; i++)
    {
        interleaver_index(i*2) = even_interleaver(i);
        interleaver_index(i*2+1) = odd_interleaver(i);
    }

    cout << d << endl;
    cout << interleaver_index << endl;

    frame_interleaver.set_interleaver_depth(d.length());
    frame_interleaver.set_interleaver_sequence(interleaver_index);
    vec e = frame_interleaver.interleave(d);
    vec interleaved_d = concat(e,b_tails,c_tails);

    return interleaved_d;
}

void EQ_Interleaver::deinterleave(vec interleaved_d, vec &a, vec &b, vec &c)
{
    vec tail = interleaved_d.right(6);
    vec tail_c = tail.right(3);
    vec tail_b = tail.left(3);

    cout << interleaved_d << endl;
    interleaved_d.del(interleaved_d.length()-6, interleaved_d.length()-1);
    vec d = frame_interleaver.deinterleave(interleaved_d);
    cout << d << endl;

    a = d.left(d.length()/3);
    b = d.mid(a.length(),a.length());
    c = d.right(d.length()/3);

    ivec index = to_ivec(linspace(a.length()-1,0,a.length()));
    b = b(index);
    c = c(index);

    b = concat(b,tail_b);
    c = concat(c,tail_c);
}
