function s = BR_dist_or(s_in)
% BR_dist_or - distributes v in logical expression (exponential time)
% On input:
%     s_in (string): logical string
% On output:
%     s (string): s_in with (a^b)vc replaced with (avc)^(bvc)
% Call:
%     s1 = BR_dist_or(s)
% Author:
%     T. Henderson
%     UU
%     Fall 2018
%

OR_OP = 'v';
AND_OP = '^';
LEFT_PAR = '(';
RIGHT_PAR = ')';

s = s_in;
index = 0;
change = 1;

while change==1
    len_s = length(s);
    if index>=len_s
        change = 0;
    end
    index = index + 1;
    while index<=len_s&s(index)~=OR_OP
        index = index + 1;
    end
    if index<len_s
        count = 1;
        index1 = index - 1;
        while count>0
            index1 = index1 - 1;
            if s(index1)==LEFT_PAR
                count = count - 1;
            elseif s(index1)==RIGHT_PAR
                count = count + 1;
            end
        end
        S1 = s(index1:index-1);
        count = 1;
        index2 = index + 1;
        while count>0
            index2 = index2 + 1;
            if s(index2)==LEFT_PAR
                count = count + 1;
            elseif s(index2)==RIGHT_PAR
                count = count - 1;
            end
        end
        S2 = s(index+1:index2);
        if BR_isANDop(S1)
            [S11,S12] = BR_getANDargs(S1);
            prefix = s(1:index1-1);
            postfix = s(index2+1:end);
            middle = ['(',S11,OR_OP,S2,')^(',S12,OR_OP,S2,')'];
            s = [prefix,middle,postfix];
            change = 1;
            index = 0;
        elseif BR_isANDop(S2)
            [S21,S22] = BR_getANDargs(S2);
            prefix = s(1:index1-1);
            postfix = s(index2+1:end);
            middle = [LEFT_PAR,S1,OR_OP,S21,')^(',S1,OR_OP,S22,RIGHT_PAR];
            s = [prefix,middle,postfix];
            change = 1;
            index = 0;
        end
    end
end
