function postProcessFailed = covisMatlabPostProcessJob(deviceid,filenamesIn)
%% ---------------------------------------------------------------------
% General:  Daily post-process job to generate mat files from tar files for
%           COVIS sonar system
% Input:    deviceid
%           filenamesIn {cell array, string matrix or a 1-D string with comma seperated filenames}
% Output:   postProcessFailed (boolean)
%
% Comments: If the filenamesIn are not present in the current directory, the files will be retrieved from the archive if they exist.
%
%           To run this code in CodeRunner, supply the usual COVIS deviceid and an appropriate filename. This function is not
%           sensitive to the exact filename, just the date and delimiting characters '-' and '_'. The format for the filename is:
%           deviceName_startdate_enddate-aux.tar   The enddate is optional. It and the deviceName can be anything as they will be
%           ignored and overridden by the name of the file retrieved from the database. The aux field must be either 'IMAGING' or 
%           'DIFFUSE'. Here are some examples:
%
%           >> covisMatlabPostProcessJob(19003,'testCovis_20120101T000000-IMAGING.tar')
%           In this case, the IMAGING file immediately after the startdate will be processed.
%
%           >> covisMatlabPostProcessJob(19003,'testCovis_20120101T000000-IMAGING.tar,testCovis_20120102T030000-IMAGING.tar')
%           In this case, the code will loop over the two file names provided. If one wants to process one full day of data, 
%           you will have to loop over eight filenames - the usual configuration generates files shortly after 00 03 06 09 12 15 18 21
%           hours UTC. The other option is to use getCOVISdp. See that function for more help.
%
% Modify Date/Author:  20120705, B.Biffard - see SVN history for revisions
%---------------------------------------------------------------------

%% check inputs
if nargin~=2
    error('NEPTUNE:covisMatlabPostProcessJob','Input parameters missing for covisMatlabPostProcessJob'); 
else
    if ischar(deviceid)
        if any(isletter(deviceid))
            error('NEPTUNE:covisMatlabPostProcessJob','Input parameter deviceid cannot contain any letters, even if it is input as a string')            
        end
        deviceid = str2double(deviceid);
    end
    if isnumeric(filenamesIn)
        error('NEPTUNE:covisMatlabPostProcessJob','Input parameter filenamesIn cannot be a numeric'); 
    elseif ~iscellstr(filenamesIn)        
        if any(filenamesIn==',') && any(size(filenamesIn)==1)  %string with comma seperated filenames
            filenamesIn = textscan(filenamesIn,'%s','delimiter',',');
        else
            filenamesIn = cellstr(filenamesIn);   %string matrix
        end
    end
end

%% set up constants and variables
postProcessFailed = false;
dpnames = {};
errorMsg = '';
warning('off', 'MATLAB:colorbar:DeprecatedV6Argument')
searchDetails.searchid=-1;
searchDetails.networkid=NaN;
searchDetails.resultid=1;

%% run the dp code
nFile = length(filenamesIn);
if nFile>0
    for iFile = 1:nFile
        try                 
            %set the start and end dates equal to a full day.
            [~,n,~]=fileparts(filenamesIn{iFile});
            ndi = strfind(n,'-'); 
            n = n(1:ndi(end)-1); %trim off the ancillary info and extra extensions in the case of .tar.gz
            nui = strfind(n,'_'); 
            if length(nui) < 2
                nui(2) = length(n)+1;
            end
            [~,sd,~] = fileparts(n(nui(1)+1:nui(2)-1));
            startdate = datenum(sd,'yyyymmddTHHMMSS');
            enddate = startdate + 1;
            
            %decide between IMAGING or DIFFUSE data products
            if strfind(filenamesIn{iFile},'IMAGING')
                searchDetails.dataproductformatid = 70;
                searchDetails.dataproductid = 40;
                searchDetails.archivefileextensionid = 9;
            elseif strfind(filenamesIn{iFile},'DIFFUSE')   
                searchDetails.dataproductformatid = 72;
                searchDetails.dataproductid = 41;
                searchDetails.archivefileextensionid = 9;
            else
                error('NEPTUNE:covisMatlabPostProcess',['Cannot determine if the given COVIS file name ''' filenamesIn{iFile} ''' is an IMAGING or DIFFUSE file']);
            end              
            
            [dpfiles, dpErrorMsg] = getCOVISdp(deviceid,startdate,enddate,searchDetails,1);
            dpnames = [dpnames; dpfiles]; %#ok<*AGROW>

            if ~isempty(dpErrorMsg)
                errorMsg = [errorMsg ' ' filenamesIn{iFile} ': ' dpErrorMsg];
            end 
        catch ME
            if exist('ME','var')
                errorMsg = [errorMsg ME.message ' '];  %#ok<AGROW>
                disp(' ')
                disp(getReport(ME))
                disp(' ')
            end
        end 
    end
else
    errorMsg = 'Error: No files specified to process';
end     

%% write results to txt file for java to read
fid = fopen('covisMatlabPostProcessResults.txt', 'wt');
for i = 1:size(dpnames)
    fprintf(fid, '%s\n', dpnames{i});
end
fprintf(fid, '%s\n', '##########');

%% check on error messages
if ~isempty(errorMsg)
    postProcessFailed = true;
    fprintf(fid, '%s\n', errorMsg); 
end 
fclose(fid);

    




