function Sa = interp_asce_spectrum(T_query, spec)
% interp_asce_spectrum
%
% Interpolates ASCE 7-22 response spectrum using log-log interpolation
%
% INPUTS:
%   T_query : scalar or vector of periods (sec)
%   spec    : Nx2 array [Period (sec), Acceleration (g)]
%
% OUTPUT:
%   Sa      : interpolated spectral acceleration (g)
%
% NOTES:
%   - Uses log-log interpolation (recommended for response spectra)
%   - Issues warnings if query period is out of range

    % --- Input checks ---
    if size(spec,2) ~= 2
        error('spec must be Nx2: [Period(sec), Accel(g)]');
    end

    T_spec = spec(:,1);
    Sa_spec = spec(:,2);

    % Ensure column vectors
    T_spec = T_spec(:);
    Sa_spec = Sa_spec(:);

    % Sort just in case
    [T_spec, idx] = sort(T_spec);
    Sa_spec = Sa_spec(idx);

    % Preallocate
    Sa = zeros(size(T_query));

    % Range
    T_min = min(T_spec);
    T_max = max(T_spec);

    % --- Warnings for out-of-range ---
    if any(T_query < T_min)
        warning('Some query periods are below spectrum range (T < %.4g sec). Extrapolation will be used.', T_min);
    end

    if any(T_query > T_max)
        warning('Some query periods are above spectrum range (T > %.4g sec). Extrapolation will be used.', T_max);
    end

    % --- Log-log interpolation ---
    % Avoid log(0) issues
    if any(T_spec <= 0) || any(Sa_spec <= 0)
        error('Spectrum contains non-positive values. Log interpolation requires T > 0 and Sa > 0.');
    end

    logT_spec = log(T_spec);
    logSa_spec = log(Sa_spec);

    % Interpolate in log space
    logT_query = log(T_query);

    logSa = interp1(logT_spec, logSa_spec, logT_query, 'linear', 'extrap');

    % Back to linear space
    Sa = exp(logSa);

end