clc; clear
couplingNumber = 0.1;
characteristicLength = 0.1*0.04;
microInertia = 0.01;
pres = 4e6;
resFolder = sprintf('Result\\CN_%g_LB_%g_J0_%g_S0_%g\\', couplingNumber, ...
    characteristicLength*1e3, microInertia, pres/1e6);
load([resFolder, 'init'])
totStep = init.nrecord;
timeSteps = totStep:1:totStep;
%timeSteps = 463;
 timeSteps = 10:1:390;

x = init.x;
y = init.y;

ims = cell(numel(timeSteps),1);
for i = 1:numel(timeSteps)
    step = timeSteps(i);
    stepFile = [resFolder,sprintf('step%d.mat',step)];
    if(~exist(stepFile, 'file'))
        break;
    end
    load(stepFile);
    figh = figure(200); clf
    set(figh, 'Position', [100, 100, 600, 320*3/4])
    set(gca, 'color', 'none');
    set(gcf,'color','w')
    %     h = pcolor(x,y,reshape(step.U2,size(x)));
    %     set(h, 'edgecolor', 'none');
    Value = step.dmg(:);
    zoomRatio = 40;
    disp1 = step.U1 * zoomRatio;
    disp2 = step.U2 * zoomRatio;
%          Value(Value<0.40) = nan;
%          Value(Value>=0.40) = 1;
    scatter (x(:)+disp1(:), y(:)+disp2(:), 4, Value(:), 'filled')
    %g =  imagesc(x(1,1:end), y(1:end,1), reshape(Value, size(x)));
    colormap(jet(10));
    %colorbar;
    axis('equal'); axis([0-0.004,0.1+0.004, -0.02-0.004, 0.02+0.004]*1);
   ch = colorbar;
    isdmg = 1;
    if(isdmg)
        caxis([0,1])
        set(ch, 'Ticks', linspace(0, 1.0, 6))
    else
        set(ch, 'Ticks', linspace(min(Value), max(Value), 6))
    end
    xlabel('$\it{x}{\rm{(m)}}$', 'interpreter', 'latex', ...
        'fontsize', 16, 'fontname', 'times new roman')
    ylabel('$\it{y}{\rm{(m)}}$', 'interpreter', 'latex', ...
        'fontsize', 16, 'fontname', 'times new roman')
    titleText = sprintf('$\\it{t}=\\rm{%g}\\rm{\\mu{s}}$', step.currentTime*1e6);
    title(titleText, 'interpreter', 'latex', 'fontsize', 16, 'fontname', 'times new roman')
    box on
    set(gca, 'fontsize', 14, 'fontname', 'times new roman',...
        'xtick', 0:0.02:0.1, 'ytick', -0.02:0.01:0.02, ...
        'xminortick', 'on', 'yminortick', 'on');
    pause(0.01)
    frame = getframe(figh);
    ims{i}=frame2im(frame);
end
filename = 'dynamicDamage.gif';
delayTime = 0.2;
togif (ims, filename, delayTime);


function togif(ims, filename, delayTime)
nImages = numel(ims);
for idx = 1:nImages
    if(isempty(ims{idx})) 
        break; 
    end
    [A,map] = rgb2ind(ims{idx},256);
    if idx == 1
        imwrite(A,map,filename,'gif','LoopCount',Inf,'DelayTime',delayTime);
    else
        imwrite(A,map,filename,'gif','WriteMode','append','DelayTime',delayTime);
    end
end

end

