function [trels_edges] = make_trellis(instream, n, p)
% Construct a memory image of the desired Trellis.
% instream is a sequence of formatted ASCII numeric strings representing
% src_row, dst_row; input (real), input (imag); symbol (real), symbol (imag); ...
% (Note the meanings of the 3 delimiters: space, comma, semicolon.)
% (Example: instream = "1 1, 1.23 4.56, 7.89 -0.12; 1 2, -3.45 6.78, 9.01 2.34"
% .. represents src1=1 dst1=1, input1= 1.23+i*4.56, symbol1=7.89-i*0.12; 
% ..            src2=1 dst2=2, input2=-3.45+i*6.78, symbol2=9.01+i*2.34
% n is the number of encoder states.
% p is the number of distinct code symbols.
% n*p is the number of input pairs.
%
% D.Bozarth 03-16-08 SSU Engineering Science
%
[src dst in0 in1 sy0 sy1] = strread(instream, '%d %d %f %f %f %f', 'delimiter', ',; ');

k = n * p; 
sz_req = [k 1; k 1; k 1; k 1; k 1; k 1];
sz_tst = [size(src); size(dst); size(in0); size(in1); size(sy0); size(sy1)];

if sz_tst ~= sz_req
    error = 'Size mismatch in Trellis definition.'
    sz_req
    sz_tst
    return;
end

trels_edges = zeros(k, 1, 3); % The returned array.
trels_tmp   = zeros(k, 4);    % Extra value keeps track of the source row#.

for i = 1:k
    trels_tmp(i, 1) = dst(i);
    trels_tmp(i, 2) = complex(in0(i), in1(i));
    trels_tmp(i, 3) = complex(sy0(i), sy1(i));
    trels_tmp(i, 4) = src(i);
end

trels_tmp = sortrows(trels_tmp, [4 1]); % Sort first by src, then by dst.

for i = 1:k
    if (trels_tmp(i, 4) ~= floor((i - 1) / p) + 1) ...
            | (trels_tmp(i, 1) < 1) | (n < trels_tmp(i, 1)) 
        error = 'Incorrect Trellis definition.'
        i
        trels_tmp
        return;
    end
    
    for j = 1:3
        trels_edges(i, 1, j) = trels_tmp(i, j);
    end
end
% end function