function phi = window_lossfun(p)
%% Loss function for creating a simple flattop window
if any(p<0); phi = inf; return; end
N = 1024; [w,~,s] = p_to_window(p,N); % Get the window
W = log10( abs(fft(w))/N ); W = W(1:20); % First 20 samples of the FT of w
phi = ... Loss function
    max( [log10(sqrt((W(2)-W(1)).^2)) -2] ) + ... Top flatness
    max( [median(W(3:end)) -6] ) + ... Sidelobe magnitude
    max( diff(W(6:end)).^2 ) + ... % Sidelobe flatness
    (s-1).^2; % Window scaling factor distance from unity
end