function scenario = animatePath(scenario_file, traj_t, traj_x, gif_filename)
% Animates the trajectory given by times traj_t and states traj_x for
% scenario given by scenario_file. If gif_filename is given, a gif is made.

do_save_gif = nargin > 3;

fig = figure;
hold on
ax = gca;

scenario = ScenarioDescription(scenario_file);

frame_center = [0,0];

dt = traj_t(2)-traj_t(1);
skip = 5;
fps = skip/dt;
frames = [];
last_t = 0;
for i = 1:skip:length(traj_t)
    tic
    if ~ishandle(fig)
        break
    end
    zoox_pos = traj_x(i,1:2);
    zoox_angle = traj_x(i,3);
    scenario.drawFrame(ax, frame_center, zoox_pos, zoox_angle, traj_t(i));
    if do_save_gif
        frames = [frames, getframe];
    end

    if i == length(traj_t)
        dt = 0;
    else
        dt = traj_t(i) - last_t;
        last_t = traj_t(i);
    end
    pause(dt - toc)
end

if do_save_gif
    writeGif(gif_filename,frames,fps,1)
end