function n_flight = LEM_deconflict(s_flights,flight,hd)
% LEM_deconflict - uses FAA-NASA approach for deconfliction
% On input:
%     s_flights (flights struct): scheduled flights
%     flight (flight struct): new flight
%     h_x (float): headway distance
% On output:
%     n_flight (flight struct): new scheduled flight
% Call:
%     n_flight = LEM_deconflict(s_flights,n_flight,h_x);
% Author:
%     T. Henderson
%     UU
%     Spring 2020
%

OFFSET = 5;

n_flight = flight;
num_s_flights = length(s_flights);

if num_s_flights<1
    return
end

traj1 = flight.path_vertexes;
d11 = norm(traj1(1,4:6)-traj1(1,1:3));
d12 = norm(traj1(2,4:6)-traj1(2,1:3));
d13 = norm(traj1(3,4:6)-traj1(3,1:3));
s1 = flight.speed;

OK = zeros(num_s_flights,1);
done = 0;
while done==0
    s = 0;
    while s<num_s_flights
        s = s + 1;
        traj2 = s_flights(s).path_vertexes;
        s2 = s_flights(s).speed;
        d21 = norm(traj2(1,4:6)-traj2(1,1:3));
        d22 = norm(traj2(2,4:6)-traj2(2,1:3));
        d23 = norm(traj2(3,4:6)-traj2(3,1:3));
        ind1 = 0;
        while ind1<3
            ind1 = ind1 + 1;
            ind2 = 0;
            p11 = traj1(ind1,1:3);
            p12 = traj1(ind1,4:6);
            if ind1==1
                t11 = n_flight.start_time;
            elseif ind1==2
                t11 = n_flight.start_time + d11/s1;
            else
                t11 = n_flight.start_time + (d11+d12)/s1;
            end
            while ind2<3
                ind2 = ind2 + 1;
                p21 = traj2(ind2,1:3);
                p22 = traj2(ind2,4:6);
                if ind2==1
                    t21 = s_flights(s).start_time;
                elseif ind2==2
                    t21 = s_flights(s).start_time + d21/s2;
                else
                    t21 = s_flights(s).start_time + (d21+d22)/s2;
                end
                [b,min_d,t_cpa] = LEM_CPA(p11,p12,s1,t11,p21,p22,s2,t21,hd);
                if b==1
                    ind1 = 3;
                    ind2 = 3;
                    s = num_s_flights;
                    n_flight.start_time = n_flight.start_time + OFFSET;
                    if n_flight.start_time>n_flight.start_interval(2)
                        done = 1;
                    end
                end
            end
        end
        if s==num_s_flights&done==0
            done = 1;
        end
    end
end
