function code_out=conv_enc( input_bit, next_state, output, N_IN, N_OUT, N_STATE)

% Convolutional Encoder
%
% code_out = conv_enc( input_bit, next_state, output )
%
% input_bit : binary input bit stream (message)
% next_state : Next state matrix  (can be generated from trellis function) (N_STATE by 2^N_IN)
% output : Output codeword matrix (can be generated from trellis function) (N_STATE by 2^N_IN)
% N_IN  : number of input bits of the encoder
% N_OUT : number of output bits of the encoder
% N_STATE : number of state of the convolutional code
%
% input_bit and code_ouput orderings are as follows
%
% input_bit=
% [ input_bit1 intput_bit2 input_bit3 ... input_bitN_IN   input_bitN_IN+1 ... ]
%    1st        2nd           3rd     ...    N_IN th         1st                : Encoder input feeding order
%
% code_out=
% [ output_bit1 output_bit2 output_bit3 ... output_bitN_OUT output_bitN_OUT+1 ...]
%    1st          2nd          3rd           N_OUT th             1st           : Encoder output order
%
% Assumes the zero initial state (achieved by zero tail bits in the previous message)
% The length of input_bit should be the multiple of N_IN

if nargin~=6
    error('Wrong number of input arguments');
    return;
elseif prod(double(size(next_state)==size(output)))==0
    error('Dimension of next_state should be the same as that of output');
    return;
elseif prod(double(size(next_state)==[N_STATE 2^N_IN]))==0
    error('N_STATE or N_IN is not compatible with the size of next_state');
    return;
end

L_MESSAGE=length(input_bit);
N_CODE=L_MESSAGE/N_IN;

if N_CODE ~= round (L_MESSAGE/N_IN)
    error('Length of input bit stream should be the integer multiple of the number of input bits of the encoder!');
    return;
end

%Output initialization
code_out=zeros(1,N_CODE*N_OUT);

for i=1:N_CODE
    
    start_index=(i-1)*N_IN+1;
    input_dec=2.^(0:N_IN-1)*(input_bit(start_index:start_index+N_IN-1))'; %input codeword (convert from binary to decimal)
    
    if i==1
        cur_state=0;
    end
    
    %Convert the output codeword into binary vector
    
    code_out((i-1)*N_OUT+1:i*N_OUT)=bitget(output(cur_state+1,input_dec+1),1:N_OUT);
    cur_state = next_state(cur_state +1 , input_dec +1 );
    
end