function fwhm = computeFWHM(x, y, xo)
% fwhm = computeFWHM(x, y, xo)
% ChatGPT request: "write a matlab function that accepts a time series x,y,
% and computes the full width at half maximum of the of the peak in y
% nearest xo If xo is omitted, it computes the halfwidth from the maximum y
% value."

  % Find the nearest x value to xo
  [~, i] = min(abs(x - xo));
  
  % Find the maximum y value within a certain range around the nearest x value
  ymax = max(y(max(1, i - 10):min(length(y), i + 10)));
  imax = find(y == ymax);
  
  % If xo is not provided, use the x value of the maximum y as the reference point
  if nargin < 3
    xo = x(imax);
  end
  
  % Find the half maximum value
  yhalf = ymax / 2;
  
  % Find the indices of the points where y crosses the half maximum value
  i1 = find(y(1:imax) < yhalf, 1, 'last');
  i2 = find(y(imax:end) < yhalf, 1, 'first') + imax - 1;
  
  % Calculate the full width at half maximum
  fwhm = abs(x(i2) - x(i1));
end
