function res = LEM_sim4(x_min,x_max,y_min,y_max,del_x,min_lane_len,...
    t_min,t_max,del_t,lambda,launch_interval,speeds,sigma,p1,p2)
% LEM_sim4 - robust FAA-NASA vs LSD simulation - LSD part
% On input:
%     x_min (float): min x values in roads
%     x_max (float): max x values in roads
%     y_min (float): min y values in roads
%     y_max (float): max y values in roads
%     del_x (float): distance between intersections in grid road layout
%     min_lane_len (float): minimum lane length
%     t_min (float): min sim time
%     t_max (float): max sim time
%     del_t (float): time step
%     lambda (float): mean interarrival time (in secs)
%     launch_interval (float): possible launch time spread
%     speeds (1x2 vector): [min_speed, max_speed]
%     sigma (float): varince (in each dimension) of flight position
%     p1 (float): percent of ground vertexes to be launch vertexes
%     p2 (float): percent of ground vertexes to be land vertexes
% On output:
%     res (results struct): results of simulation
%       .requests (requests struct): list of flight requests
%       .reservations (reservations struct): actual reservations
%       .flights (flights struct): flight info
% Call:
%     res = LEM_sim4(-18500,18500,-11500,11500,2000,10,0,10000,1,0.5,4,...
%                     [30,30],0.1,0.1,0.1);
% Author:
%     T. Henderson
%     UU
%     Fall 2020
%

% 7 mi (37000') by 4.3(23000') mi; intersections at 2000' intervals
roads = LEM_grid_roads(x_min,x_max,y_min,y_max,del_x,del_x);
num_gv = length(roads.vertexes(:,1));
l1 = randperm(num_gv);
l1 = l1(1:ceil(p1*num_gv));
l2 = randperm(num_gv);
l2 = l2(1:ceil(p2*num_gv));
airways = LEM_gen_airways(roads,l1,l2,min_lane_len);
num_lanes = length(airways.lanes(:,1));
for k = 1:num_lanes
    reservations(k).flights = [];
end
flights = [];
num_flights = 0;
[requests,times] = LEM_gen_requests(t_min,t_max,airways,lambda,...
    launch_interval,speeds);

t = -del_t;
wb = waitbar(0,'Flight Sim 4');
while t<t_max
    waitbar(t/t_max);
    t = t + del_t;
    [t,t_max];
    new_flights = [];
    indexes = find(times>=t&times<t+del_t);
    if ~isempty(indexes)
        num_indexes = length(indexes);
        for n = 1:num_indexes
            [reservations,new_flights] = LEM_gen_reservations(airways,...
                flights,reservations,t,1);
        end
    end
    if ~isempty(new_flights)
        num_new_flights = length(new_flights);
        for k = 1:num_new_flights
            flights(end+1).type = new_flights(k).type;
            flights(end).plan = new_flights(k).plan;
            flights(end).route = new_flights(k).route;
            flights(end).telemetry = new_flights(k).telemetry;
        end
    end
    new_flights = LEM_gen_rogue_flights(airways,flights,t);
    flights = LEM_advance_flights(flights,t,del_t,sigma);
end
close(wb);
res.roads = roads;
res.airways = airways;
res.reservations = reservations;
res.flights = flights;
