function [ilist] = get_ilist(cfg, last_index)
% trap for obvious errors
% [1:step:end] overrides ilist overrides irange overrides ends
% 'step' implimented for irange 

%(1)  look for errors
if (~ismember(cfg.ends, [0 1 2 4]))
   error(' option "ends" must be 0,1,2, or 4')
end


if (diff(cfg.irange)<=0)
   error('irange must increase\n')
end


if (length(cfg.irange) > 2)
   fprintf('---> ''irange'' was a list: ')
   fprintf('using index endpoints [%d %d] for range.\n', ...
           cfg.irange(1), cfg.irange(end))
   cfg.irange = cfg.irange([1 end]);
end


% default
ilist = 1:cfg.step:last_index;

if (~isempty(cfg.ilist))  %this was an explicit index list
   ilist = cfg.ilist;
elseif (~isempty(cfg.irange))
   ilist = [cfg.irange(1) : cfg.step : min(cfg.irange(end), last_index)]';
elseif (~isempty(cfg.ends) & (cfg.ends > 0))
   if (cfg.ends == 4)
      ilist = sort(unique([1, 2, (last_index - 1), last_index]));
      ilist = ilist(find(   (ilist <= last_index) & (ilist >= 1)));
   elseif (cfg.ends == 2)
      ilist = sort(unique([1 last_index]));
   else %it has to be 1 because we checked it before
      ilist = 1;
   end
end


%toss out indices that are too small
badi = find(ilist < 1);
if (~isempty(badi))
   ilist(badi)=[];
   if (cfg.verbose)
      fprintf('part of ilist smaller than 1: truncating\n')
   end
end

%toss out indices that are too large
badi = find(ilist > last_index);
if (~isempty(badi))
   ilist(badi)=[];
   if (cfg.verbose)
      fprintf('part of ilist excedes last index: truncating after %d\n',...
              last_index)
   end
end

if (isempty(cfg.ilist) & ...
    (isempty(cfg.ends)) & ...
    (isempty(cfg.irange)) & ...
    (isempty(ilist)))
   error('no indices found')
end


