function [OUT,ISCODON] = unfiltered2filtered(IN, filter, h, varargin)
% this function take in a cell array of strings that contains nucleotide
% sequences (IN variable) and also a filter, in form of 
% filter = 'TCT~~~TGT~~~~~~~~~TGTGGTGGAGGT';
% where ~ designates any nucleotide and the other nucleotides are part of
% filter. It then look for all nucleotides that are withing a h -distance
% of the filter (use h=1 for loose filtering and h=0 for super sctrict
% filtering)

if exist('varargin','var')
    L = length(varargin);
    if rem(L,2) ~= 0, error('Parameters/Values must come in pairs.'); 
    end

    % read input variables
    for ni = 1:2:L
        switch lower(varargin{ni})
            case 'codons',      codons = varargin{ni+1};
            case 'positions',   positions = varargin{ni+1};
        end
    end
end 


cIN = char(IN);
cIN = cIN(:,1:numel(filter)); % truncate the reads to filter length

MAX = min (abs('ATCG '-'~~~~~'));  % precalculate maximum allowable difference

Afilter = makearray(filter,size(IN,1));  %replicate the filter into array form

D = abs(cIN-Afilter);  % calculate the absolute difference

% if all values are zero, the sum iz zero, if there is one mismatch with
% the filter, the sum is 1, if there is more than one, then the read is not
% considered

sumD = sum ( ~( (D >= MAX) | (D == 0) ),2 );  

% the function returns the indices of the reads that match the filter
OUT = find(sumD<=h);

end

function [aSEQ] = makearray(SEQ,SIZE)

    aSEQ = ones(SIZE,numel(SEQ));
    
    for i=1:numel(SEQ)
        aSEQ(:,i)=SEQ(i);
    end
    
    aSEQ = char(aSEQ);

end