function [perf_measure,percent_clean,num_moves,trace] = ...
    CS6380_Assgn1_run_sim(num_agents,percent_dirt,...
    max_time,num_rows,num_cols)
% CS6380_Assgn1_run_sim - run cleaning reflex agent simulation
% On input:
%     num_agents (int): number of agents
%     percent_dirt (float): percentage of cells to contain dirt
%     max_time (int): max number of steps in simulation
%     num_rows (int): number of rows in area
%     num_cols (int): number of cols in area
%     trace (num_steps,2*num_agents array): agent locations at each step
% On output:
%     perf_measure (float): performance measure: best time over actual time
%     percent_clean (float): percentage of area that is clean
%     num_moves (int): number of moves
% Call:
%     [pm,pc,nm,rt] = CS6380_Assgn1_run_sim(10,0.4,100,20,20)
% Author:
%     T. Henderson
%     UU
%     Summer 2014
%

trace = [];
best_perf = num_rows*num_cols;
current_time = 0;
agents = CS6380_Assgn1_init_agents(num_agents);
area = CS6380_Assgn1_put_dirt(num_rows,num_cols,percent_dirt);
all_clean = 0;
actions = zeros(1,num_agents);
num_moves = 0;
while current_time<max_time&(~(all_clean==1))
    current_time = current_time + 1;
    locs = zeros(1,num_agents);
    for a = 1:num_agents
        percept = area(agents(a).row,agents(a).col);
        actions(a) = CS6380_Assgn1_reflex_agent(percept);
        locs((a-1)*2 + 1) = agents(a).row;
        locs((a-1)*2 + 2) = agents(a).col;
    end
    trace = [trace;locs];
    for a = 1:num_agents
        switch actions(a)
            case 1   % clean
                area(agents(a).row,agents(a).col) = 0;
            case 2   % move right
                agents(a).col = min(num_cols,agents(a).col+1);
            case 3   % move up and right
                agents(a).col = min(num_cols,agents(a).col+1);
                agents(a).row = max(1,agents(a).row-1);
            case 4   % move up and left
                agents(a).col = max(1,agents(a).col-1);
                agents(a).row = max(1,agents(a).row-1);
            case 5   % move left
                agents(a).col = max(1,agents(a).col-1);
            case 6   % move down and left
                agents(a).col = max(1,agents(a).col-1);
                agents(a).row = min(num_rows,agents(a).row+1);
            case 7   % move down
                agents(a).row = min(num_rows,agents(a).row+1);
            case 8   % move down and right
                agents(a).col = min(num_cols,agents(a).col+1);
                agents(a).row = min(num_rows,agents(a).row+1);
        end
        if actions(a)~=1
            num_moves = num_moves + 1;
        end
    end
    if sum(sum(area))==0
        all_clean = 1;
    end
end
perf_measure = current_time;
percent_clean = 1 - sum(sum(area))/(best_perf);
tch = 0;
