%
%--------------------------------------------------------------------------
% function [agilent]=FT_read_Agilent6000_ascii(filename)
%
% A function for Matlab which reads an ascii data file saved by
% an Agilent 6000 scope.
%
% filename: base name of the ASCII data file, eg. 'scope_4'
% agilent:  the data and header info stored as:
%           agilent.filename: basename of data files
%           agilent.channels: number of channels
%           agilent.samples:  number of samples
%           agilent.x_data:   xaxis (row vector of agilent.samples length)
%           agilent.ch_data:  channel data, 
%                             matrix (agilent.samples x agilent.channels)
%
% Part of the SimTools package
% Andreas Freise, Simon Chelkowski 05.02.2010 afreise@googlemail.com
%--------------------------------------------------------------------------
%

% Description: Reads an ascii data file saved by an Agilent 6000 scope
% Keywords: read, Agilent6000, ascii, data

function [agilent]=FT_read_Agilent6000_ascii(filename)

  %% test if first channel file exists
    
    baseid='read_Agilent6000_ascii';

    no_headerlines = 2;    % These number of headerlines refer to the data saved with the Agilent 6000

    agilent.filename=filename;
    
    % determine number of channels
    agilent.channels=0;
    for i=1:4
      tmp_name=sprintf('%s_%d.csv',filename,i);
      if exist(tmp_name)
        ch_name{agilent.channels+1}=tmp_name;
        agilent.channels=agilent.channels+1;        
      end
    end
        
    fprintf(' Found %d channel(s).\n',agilent.channels);

    if (agilent.channels==0)
      msgid=[baseid,':filename'];
      result=sprintf('Cannot find any channel files named %s_xx.csv.\n',filename);
      error(msgid,result);
    end
    
    % find number of samples
    agilent.samples=0;
    chunksize=1e6;
    fh=fopen(cell2mat(ch_name(1)),'r');
    while ~feof(fh)
      ch = fread(fh, chunksize, '*uchar');
      if isempty(ch)
        break
      end
      agilent.samples=agilent.samples+sum(ch==sprintf('\n'));
    end
    agilent.samples=agilent.samples-1;
    fclose(fh);
    fprintf(' Reading in %d samples.\n',agilent.samples);
    
    % read data
    % define the length of the date to be read fr dlmread
    range = [no_headerlines,0,no_headerlines+agilent.samples-1,1]; 
    agilent.x_data=zeros(agilent.samples,1);
    agilent.ch_data=zeros(agilent.samples,agilent.channels);
    tmp= dlmread(cell2mat(ch_name(1)),',',range); 
    agilent.x_data=tmp(:,1);
    agilent.ch_data(:,1)=tmp(:,2);
    for i=2:agilent.channels
      tmp= dlmread(cell2mat(ch_name(i)),',',range); 
      agilent.ch_data(:,i)=tmp(:,2);
    end
    

