function [datavect, timevect] = getFrameData(channelName, ... 
                                        dataStartTime, dataDuration, varargin)
%function [datavect, timevect] = getFrameData(channelName, ...
%                                        dataStartTime, dataDuration, varargin)
% Contact: shivaraj.kandhasamy@ligo.org
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Generate frame cache for the time requested %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if length(varargin)==0
  frameType = [channelName(1) '1_C']; % first check for commissioning frames
  [rflag, frames] = system(['gw_data_find -o ' channelName(1) ' -t ' frameType ' -s ' num2str(dataStartTime) ' -e ' num2str(dataStartTime+dataDuration) ' -u file']);
  if (length(frames)<=1 | strcmp(frames,'No files found!'))
    frameType = [channelName(1) '1_R']; % try archived frames
    [rflag, frames] = system(['gw_data_find -o ' channelName(1) ' -t ' frameType ' -s ' num2str(dataStartTime) ' -e ' num2str(dataStartTime+dataDuration) ' -u file']);
  end
elseif length(varargin)==1
  frameType = [channelName(1) '1_' varargin{1}]; % user defined frame types
  [rflag, frames] = system(['gw_data_find -o ' channelName(1) ' -t ' frameType ' -s ' num2str(dataStartTime) ' -e ' num2str(dataStartTime+dataDuration) ' -u file']);
else 
  error('No. of arguements should be 3 or 4 \n');
end

if(length(frames)>1)
  % Only return non-empty frame lines     
  frames = regexp(frames,'\n','split');
  frames = frames(find( ~strcmpi(frames,'')));

  if strcmp(frames,'No files found!')
    error('gw data find found no matching frames')
  end
  % Return arrays of frame gps and duration
  gps = zeros(size(frames));
  dur = zeros(size(frames));

  datavect = [];
  timevect = [];
  for ii = 1:length(frames); % get data
    %fprintf('%d / %d\n',ii, length(frames));
    frames{ii} = strrep(frames{ii},'file://localhost','');
    frame_split = regexp(strrep(frames{ii},'.gwf',''),'-','split');
    %[tempdata, tsamp, fsamp, gps0] = frextract(frames{ii},channelName);
    % using frextract is too slow, so instead we use frgetvect; but it 
    % requires a couple more additional details (startGPS time of the frame 
    % and duration of the frame) which is available via 'frame_split' variable
    [tempdata, tsamp, fsamp, gps0] = frgetvect(frames{ii}, channelName, ...
           str2double(frame_split{end-1}), str2double(frame_split{end}));
    datavect = [datavect; tempdata];
    timevect = [timevect; tsamp+gps0];
  end
  % select data that is between given start and end time
  datavect = datavect(timevect>=dataStartTime & timevect<dataStartTime+dataDuration);
  timevect = timevect(timevect>=dataStartTime & timevect<dataStartTime+dataDuration);
  fprintf('done loading data\n');
else
  error('error running gw_data_find \n');
end

return;
