%
%  plot_avd_time_histories_subplots_title.m  ver 1.4  by Tom Irvine
%

function[fig_num]= ...
  plot_avd_time_histories_subplots_title(acceleration,velocity,displacement,iunit,fig_num,tstring)

hp = figure(fig_num);
fig_num = fig_num + 1;

%% ============================================================
% ACCELERATION
% ============================================================
subplot(3,1,1);
plot(acceleration(:,1),acceleration(:,2));
grid on;
title(sprintf('Acceleration  %s',tstring));

if(iunit==3)
    ylabel('Accel (m/sec^2)');
else
    ylabel('Accel (G)');
end

yabs = max(abs(acceleration(:,2)));
ymax = ytick_linear_scale(yabs);

apply_engineering_ticks(ymax);

%% ============================================================
% VELOCITY
% ============================================================
subplot(3,1,2);
plot(velocity(:,1),velocity(:,2));
grid on;
title('Velocity');

if(iunit==2 || iunit==3)
    ylabel('Velocity (m/sec)');
else
    ylabel('Velocity (in/sec)');
end

yabs = max(abs(velocity(:,2)));
ymax = ytick_linear_scale(yabs);

apply_engineering_ticks(ymax);

%% ============================================================
% DISPLACEMENT
% ============================================================
subplot(3,1,3);

if(iunit==2)
    displacement(:,2) = displacement(:,2) * 1000;
end

plot(displacement(:,1),displacement(:,2));
grid on;
title('Displacement');
xlabel('Time (sec)');

if(iunit==2 || iunit==3)
    ylabel('Disp (mm)');
else
    ylabel('Disp (in)');
end

yabs = max(abs(displacement(:,2)));
ymax = ytick_linear_scale(yabs);

apply_engineering_ticks(ymax);

set(hp,'Position',[50 50 650 650]);

end


function apply_engineering_ticks(ymax)

    ymax = abs(ymax);
    
    % Determine magnitude
    exp10 = floor(log10(ymax));
    scale = 10^exp10;
    
    % Normalize
    mant = ymax / scale;
    
    % Engineering rounding sequence
    nice = [1 2 4 5 8 10];
    
    idx = find(mant <= nice,1,'first');
    
    ymax_nice = nice(idx) * scale;
    
    % Axis limits
    ylim([-ymax_nice ymax_nice])
    
    % Tick spacing
    step = ymax_nice / 2;
    
    % Symmetric ticks
    yticks(-ymax_nice:step:ymax_nice)

end


% ==============================================================
%  ytick_linear_scale.m  ver 1.1  by Tom Irvine
% ==============================================================

function[ymax]=ytick_linear_scale(yabs)

ymax = 0;

for i = -12:12

    eee = 10^i;

    if(yabs <= 0.13*eee)
        ymax = 0.15*eee;
        break;
    end

    if(yabs <= 0.18*eee)
        ymax = 0.2*eee;
        break;
    end

    if(yabs <= 0.38*eee)
        ymax = 0.4*eee;
        break;
    end

    if(yabs <= 0.48*eee)
        ymax = 0.5*eee;
        break;
    end

    if(yabs <= 0.96*eee)
        ymax = 1.0*eee;
        break;
    end

end

end