function [k,idx,sigma,med] = segmented_median2(data,n)
% segmented_median.m -- The idea is to find an offset for data.
% Data is assumed to contain periods of variation (lightning)
% As well as relatively quiet periods.  The median value
% of the quiet periods is a good "offset"
% Thus function breaks data into n segments arranged by time
% If n=5, then first segment would be first 20% of data, 2nd next
% 20% and 5th segment the last 20% of data.  I generally recommend
% n=10.  This must mean the waveform is "quiet" for at least 10%
% of the time -- and this quiet period will be found and its median
% reported.  Also reported will be the sigma and med of all n bins,
% along with the indexes that go with these bins.
siz=size(data);
if(n > 100)|| (n<3)  error('segmented_median expects a level between 3 and 100'); end
if (min(siz)>1) error('segmented_median expects row or column vector -- matrix passed.'); end
len=length(data);
idx=linspace(1,len,n+1);
idx=round(idx);
sigma=zeros(1,n);
med=zeros(1,n);
for m=1:n
    segment=data(idx(m):idx(m+1));
    sigma(m)=std(segment);
    med(m)=median(segment);
end
[minsd,k]=min(sigma);
index=idx(k);
end