function [t,data,channelList,varnames,status] = loadAgilentData(fname)
% loadAgilentData  Read measurement data exported from Benchlink
%
% Synopsis: [t,data,channelList,status] = loadAgilentData(fname)

status = 1;  %  assume positive outcome

% --- Prompt user for the input file
if nargin<1 || isempty(fname)
  try
    [fileName,pathName] = uigetfile('*','Select a tab-delimited text file for import');
    inFile = [pathName,fileName];
  catch
    errordlg('Could not open the tab-delimited plain text file');
  end
else
  inFile = fname;
end

% --- Try to detect the number of data columns in the file
ncol = countColumns(inFile);
nchan = round(ncol/2);
if ncol==0
  msg = {sprintf('No data columns detected in %s.',fileName),...
         'Please check that the file is a tab-delimited plain text file'};
  errordlg(msg);
  return;
elseif abs(ncol-2*nchan)>100*eps
  msg = {sprintf('Number of data columns in %s does not appear to be an even number.',fileName),...
         sprintf('ncol = %g,  nchan = %g',ncol,nchan),...
         ' ',...
         'Please check that the file is a tab-delimited plain text file'};
  errordlg(msg);
  return;
end

try
  ncol = 2*nchan;   %  time and value for each channel
  nhead = 0;
  nrowlabel = 1;
  [t,D,labels] = loadColData(inFile,ncol,nhead,nrowlabel);
catch
  status = -2;
  errordlg(sprintf('Could not read %s with loadColData.  Please check that the file is plain text',inFile));
  return;
end

% --- Copy imported data to 'handles' object for persistent storage
data = D(:,1:2:end);   % Measured data is in columns 2, 4, 6, ... of matrix D

% --- Update menu of column labels based on column labels for this file
iend = size(labels,1);
for i=1:size(labels,1)
  if strcmp(deblank(labels(i,:)),'')
    iend = i-1;
    break;
  end
end
labels(iend+1:end,:) = [];             %  Delete blank rows at end of 'labels' matrix
dataLabels = labels(2:2:iend,:);       %  save column labels

% --- Build and save a channel list from the column labels
channelList = dataLabels(1,1:3);     %  first three digits are always a number
for i=2:size(dataLabels,1)
  channelList = strvcat(channelList,dataLabels(i,1:3));  %  first three digits are always a number
end

% --- Create valid variable names corresponding to column headings
nvars = size(dataLabels,1);
varnames = [];
for i=1:nvars
  varnames = strvcat(varnames,sprintf('%s%s',dataLabels(i,5:7),dataLabels(i,1:3)));
end
%  disp(varnames)

% +++++++++++++++++++++++++++++++++++++++++++++++++++
function n = countColumns(fname)
% countColumns  Count the number non-whitespace strings in first line of a text file
%
% Synopsis:  n = countColumns(fname)
%
% Input: fname = (string) full path to file.  Simple file name is OK if
%                the file is in the current director
%
% Output: n = number of continuous character strings separated by whitespace
%             in the first line of the file.  If the file is a tab-delimited
%             text file, n will be the number of columns in the first line.

if ~exist(fname,'file')
  error(sprintf('"%s" does not exist in MATLAB path',fname));
end
try
  fp = fopen(fname,'r');
catch
  errordlg(sprintf('Could not open %s in countColumns()',fname));
end
% --- Read only the first line of the file, and close it.
theLine = fgetl(fp);
fclose(fp);

n = 0;                    % number of strings found
rem = theLine;            % initialize the remainder
while length(rem)>0
  [s,rem] = strtok(rem);  %  store the next string in s, remainder in rem
  n = n + 1;
end