function adfiles=getADfiles(deviceid,startdate,enddate)
%---------------------------------------------------------------------
% General:  Returns cell of AD filename strings for deviceid between
%           startdate and endddate
% Input:    deviceid (number)
%           startdate (datenum)
%           enddate (datenum)
% Output:   adfiles (cell of strings)
% Modify Date/Author:  20091126, R.Jenkyns
%           20110909, R. Jenkyns - migrated to use of archivefile table
%           from datafile table
%---------------------------------------------------------------------
if nargin<1,error('Missing required deviceid input'); end
if nargin<2, startdate=floor(now)-datenum([0 0 1 0 0 0]); end  
if nargin<3, enddate=floor(now); end    

adfiles='';

if enddate>startdate
    
    dsStart=datestr(startdate,'yyyy-mm-dd');
    if enddate-floor(enddate)==0
        dsEnd=datestr(enddate-1,'yyyy-mm-dd');
    else    
        dsEnd=datestr(enddate,'yyyy-mm-dd');
    end    

    % Establish a connection to NEPTUNE's database
    conn = connectToNeptuneEnv(getEnv);

    fprintf(['Finding archived files for ', 'device ID = %d, date >= %s\n, date <= %s\n'], ...
        deviceid, dsStart, dsEnd);

    qry = [ 'select filename from archivefile ', ...
      'where deviceid = ', sprintf('%d', deviceid), ' ', ...
      'and datefrom >= to_date(''', dsStart, ''', ''yyyy-mm-dd'') ', ...
      'and datefrom <= to_date(''', dsEnd, ''', ''yyyy-mm-dd'') ', ...
      'and filename like ''%.txt''' ];
    if deviceid==12601 % hydrophone
        qry = [ 'select filename from archivefile ', ...
          'where deviceid = ', sprintf('%d', deviceid), ' ', ...
          'and datefrom >= to_date(''', dsStart, ''', ''yyyy-mm-dd'') ', ...
          'and datefrom <= to_date(''', dsEnd, ''', ''yyyy-mm-dd'') ', ...
          'and filename like ''%.wav''' ];
    end    
    if deviceid==19003 % COVIS
        qry = [ 'select filename from archivefile ', ...
          'where deviceid = ', sprintf('%d', deviceid), ' ', ...
          'and datefrom >= to_date(''', dsStart, ''', ''yyyy-mm-dd'') ', ...
          'and datefrom <= to_date(''', dsEnd, ''', ''yyyy-mm-dd'') ', ...
          'and filename like ''%.tar''' ];
    end    

    % Execute the query
    csr = exec(conn, qry); 
    if ~isempty(csr.Message)
        close(conn);
        display(['AD file query failed: ', csr.Message]);
    else
        csr = fetch(csr); 
        if ~isempty(csr.Message)
            close(conn);
            display(['AD file fetch failed: ', csr.Message]);
        elseif ~strcmp(csr.data{1,:},'No Data')
            adfiles=csr.data;
            close(csr);
        else
            close(csr)
        end
        close(conn); % close database connection
    end    

end
