function [snd_out,linex,liney]=snd(f,s,bw,plott,fignum);

% Calc S/N+D in BW of f,s in dB
% s must be in dB
%
% Syntax: [snd_out,linex,liney]=snd(f,s,bw,plot,fignum);
%
% f og s: frekvens og spekter til signalet og st鴜en
% bw: b錸dbredde det skal beregnes snd fra
% plot: hvis det skal plottes, fignum gir nummeret til figuren

% sf: Hvis b錮e filtrert og ufiltrert skal plottes (subfigur). 
%
% linex - dc_cut , sig_low_cut, sig    , sig_high_cut
% liney - sig_val, sig_val    , sig_val, sig_val
%
% Removes 8 start bin from s
% OPTIONAL: if exist plot - plots f,s with cut frequencies in fig 11


N=length(s);
if N>2
bin_fre=f(2)-f(1);

% bw_bin=round(bw/bin_fre) +1;
bw_bin = length(s);

% locate signal, remember matlab vector starts at 0
[sig,sig_bin]  = max(s(9:bw_bin-9));
sig_bin        = sig_bin+8;
sig_fre        = (sig_bin-1)*bin_fre;

cut_dc_bin     = 8;
cut_dc_fre     = 7*bin_fre;
cut_sigmin_bin = (sig_bin-7);
cut_sigmin_fre = (sig_bin-8)*bin_fre;
cut_sigmax_bin = min(sig_bin+7,N);
cut_sigmax_fre = min(sig_bin+6,N)*bin_fre;

Sn       = [s(cut_dc_bin+1:cut_sigmin_bin-1)' s(cut_sigmax_bin+1:bw_bin)'];
Pnn_tot  = 10*log10( sum(10.^(Sn./10)) );
snd_out  = sig - Pnn_tot;


linex=[cut_dc_fre cut_sigmin_fre sig_fre cut_sigmax_fre];
liney=[sig sig sig sig];

N = N/2;
if exist('plott')
   figure(fignum);
   semilogx(f(1:bw_bin),s(1:bw_bin),'k');hold on
   semilogx(f(bw_bin:N),s(bw_bin:N),'r');
   line([linex(1) linex(1)],[liney(1) min(s)],'color','b','linestyle','-.');
   line([linex(2) linex(2)],[liney(1) min(s)],'color','r','linestyle',':');
   line([linex(4) linex(4)],[liney(1) min(s)],'color','r','linestyle',':');
   line([f(bw_bin) f(bw_bin)],[liney(1) min(s)],'color','b','linestyle','-.');
   plot([sig_fre],[sig],'ro');
   ylabel('Power Spectral Density (dB)');
   xlabel('Frequency (Hz)');
   title(['S/(N+D) = ' num2str(round(snd_out)) 'dB (' ...
   num2str(round(log2(10.^(snd_out/20))*10)/10)...
   'bit)'],'fontname','times','fontweight','bold');
   grid on;
   hold off;
   zoom on;
end;
end;
   





