function [align_length, n_errors, error_positions] = align_with_constraints_fixed_left(seq1, seq2, maximum_errors, error_cost)
%#codegen
% Finds highest scoring alignment of seq1 and seq2 that forces their left
% ends to match. So if error cost was infinite, it would simply be the
% longest matching first nucleotides on the left.

l_seq1 = length(seq1);
l_seq2 = length(seq2);
max_match_length = min( l_seq1, l_seq2 );

c = seq1(1: max_match_length)==seq2(1:max_match_length);
my_error_positions = find(c==0,maximum_errors + 1,'first');

if ~isempty(my_error_positions)    
    if length(my_error_positions)==maximum_errors+1
        c = c(1:my_error_positions(end)-1);
    end
    
    k=find(c,1,'last');
    if ~isempty(k)
        c = c(1:k(1));
    else
        c = [];
    end            
    my_error_positions = find(c==0);
end

align_length = length(c);
n_errors = length(my_error_positions);    
best_score = align_length - error_cost*n_errors;


if n_errors>0
    e_score = zeros(n_errors,1);
    for k_e=1:n_errors
        e_score(k_e) = my_error_positions(k_e) -1 - error_cost*(k_e-1);
    end
    [maybe_better_score, maybe_better_n_errors_plus_one] = max(e_score);

    if best_score < maybe_better_score
        n_errors = maybe_better_n_errors_plus_one -1;
        align_length = my_error_positions(n_errors+1) -1;    
    end
end

error_positions = zeros(maximum_errors,1);
error_positions(1:n_errors) = my_error_positions(1:n_errors);

%% Displays alignment of the sequences
%          align_pipes = repmat('|',1,align_length);
%          align_pipes(error_positions(1:n_errors))=' ';
%          alignment = [seq1(1: align_length); align_pipes ; seq2(1:align_length)]

end