function varargout=dopOverallDataRead(fileOrDir,varargin)
% dopOSCCI Mark II: dopOverallDataRead ~ 22-11-2010 (last edit)
%
% see also dopSaveGraphData
%
% imports dopOSCCI graph data .dat files.
%

% -------------------------------------------------------------------------
%     'dopOSCCI' summarises functional transcranial Doppler ultrasonography
%     (fTCD) data.  The primary function of the software is to assess the
%     hemispheric lateralization of cognitive function.
%
%     Copyright (C) 2011 the Chancellor, Masters and Scholars of the
%     University of Oxford.
% 
%     This program is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
% 
%     This program is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
% 
%     You should have received a copy of the GNU General Public License
%     along with this program.  If not, see <http://www.gnu.org/licenses/> 
%     or write to the Free Software Foundation, Inc., 51 Franklin Street,
%     Fifth Floor, Boston, MA 02110-1301, USA.
%
%     Authors: Nic Badcock, Georgina Holt, Anneka Holden, & Dorothy Bishop.
%       contact: nicholas.badcock@gmail.com
%
%     Type 'dopOSCCIlicense' for license details or see dopOSCCIlicense.txt
%

fprintf('%s\n',['Running ',mfilename]);
try
    %% set inputs
    %     inputs.varargin=varargin;
    %     inputs.turnOn={'graph'}; % graph the imported info
    %     inputs.defaults=;
    %     dgdr=setGetInputsStruct(inputs);
    dgdr.fileOrDir=fileOrDir; clear fileOrDir;
    dgdr.translation='dopOSCCI graph data read';
    dgdr.abbreviation='dgdr'; % hmm, cumbersome...
    dgdr.fileExt='.dat'; % this is what dopSaveGraphData saves to
    dgdr.out.okay=0;
    dgdr.out.saveGraphDataChs=[1 1 1 1]; % assume all
    dgdr.out.keepFiles=1; % don't remove overall data files
    if ~isempty(varargin)
        for i=1:numel(varargin)
            if numel(varargin{i})==2
                dgdr.out.keepFiles=varargin{i}; % whether or not to keep data files
            else
                dgdr.out.saveGraphDataChs=varargin{i};
            end
        end
    end
    %% what is the input?
    %% > directory
    if exist(dgdr.fileOrDir,'dir')==7
        fprintf('\t%s\n\t\t%s\n','Directory input:',dgdr.fileOrDir);
        fprintf('\t%s\n','Searching Directory...');
        %% >> file files in directory
        dgdr.contents=dir(dgdr.fileOrDir);
        dgdr.out.fileList=[];
        for i=1:length(dgdr.contents);
            dgdr.tfnl=[dgdr.fileOrDir,dgdr.contents(i).name]; % temp file name location
            if exist(dgdr.tfnl,'file')==2
                [dgdr.td dgdr.tn dgdr.tx]=fileparts(dgdr.tfnl); % get file parts
                if strcmp(dgdr.tx,dgdr.fileExt)
                    dgdr.out.fileList{end+1}=dgdr.tfnl;
                    fprintf('\t\t%s\n',dgdr.tfnl);
                end
            end
        end
        dgdr.out.n=numel(dgdr.out.fileList);
        fprintf('\t%s\n',['Found ',num2str(dgdr.out.n),' ',dgdr.fileExt,' files']);
        
        dgdr.out.okay=1;
        %% > file name location
    elseif exist(dgdr.fileOrDir,'file')==2
        fprintf('\t%s\n\t\t%s\n','File input:',dgdr.fileOrDir);
        dgdr.out.fileList{1}=dgdr.fileOrDir;
        dgdr.out.n=1;
        dgdr.out.okay=1;
    else
        fprintf('\t%s\n\t\t%s\n\t%s\n','Input can''t be found',...
            dgdr.fileOrDir, 'Could not import data');
    end
    %% read in each file
    if dgdr.out.okay
        fprintf('\t%s\n','Read file/s');
        for i=1:dgdr.out.n
            dgdr.out.data(i)=graphDataRead(dgdr.out.fileList{i},dgdr.out.saveGraphDataChs);
        end
        
        switch sum(dgdr.out.keepFiles)
            case 0 % nothing to be saved
                fprintf('\t%s\n','Deleting directory.');
                if exist(dgdr.fileOrDir,'dir')==7
                    rmdir(dgdr.fileOrDir,'s');
                else
                    delete(dgdr.fileOrDir);
                end
            case 1
                if dgdr.out.keepFiles(2)
                    fprintf('\t Deleting %u horizontal Graph Data files.\n',numel(dgdr.out.fileList));
                    for i=1:dgdr.out.n
                        delete(dgdr.out.fileList{i});
                    end
                end
        end
    end
    %% set out puts
    varargout{1}=dgdr.out;
catch err
    %% catch dopOSCCI error
    save(dopOSCCIdebug(mfilename));rethrow(err);
end
clear inputs dgdr
end

%% embedded
%% graphDataRead
function dr=graphDataRead(fileNameLoc,saveGraphDataChs)
try
    fprintf('\t\t%s\n\t%s\n','Reading:',fileNameLoc)
    dr.fileNameLoc=fileNameLoc;
    dr.im=importdata(fileNameLoc,'\t',1);
    % first row consists of sample numbers - find max and indices and we know
    % how many chs (left, right, dif, average) have been saved
    dr.fileList=[];
    for i=3:size(dr.im.textdata,1)
        dr.fileList{end+1}=dr.im.textdata{i,1};
    end
    dr.time=dr.im.data(1,:);
    dr.max=max(dr.time);
    dr.maxIndices=find(dr.time==dr.max); % can't seem to get this straight out of max
    dr.maxIndices(dr.maxIndices<10)=[]; % sometimes max = 0 (if marker is at end of epoch) therefore need to drop any early references to 0
    dr.chs=numel(dr.maxIndices);
    
    dr.n=size(dr.im.data,1)-1;
    dr.data=dr.im.data(2:end,:);
    dr.chAbb={'Left','Right','Dif','Avg'};
    dr.chInclude=saveGraphDataChs;%zeros(1,numel(dr.chAbb));
    %     for i=1:numel(dr.chAbb)
    %         if sum(cellfun('isempty',strfind(dr.im.textdata,dr.chAbb{i})))<numel(dr.im.textdata)
    %             dr.chInclude(i)=1;
    %         end
    %     end
    % add an extra index so we can use same code (below) to collect data
    if dr.time(1)~=0 % nonzero
        dr.maxIndices=[0 dr.maxIndices];
    else % group label included
        dr.maxIndices=[find(dr.time~=0,1,'first')-1 dr.maxIndices];
    end
    % put the data into channel abbreivated structure variables
    k=1;
    for i=2:numel(dr.maxIndices)
        if dr.chInclude(i-1)
            k=k+1;
            dr.(dr.chAbb{i-1})=dr.data(:,1+dr.maxIndices(k-1):dr.maxIndices(k));
        end
    end
    % put left and right together for plotting
    if sum(dr.chInclude(1:2))==2
        dr.LR(:,:,1)=dr.Left; dr.LR(:,:,2)=dr.Right;
    end
    dr=rmfield(dr,'im');
catch err
    %% catch dopOSCCI error
    save(dopOSCCIdebug(mfilename)); rethrow(err);
end
end