function varargout=dopBehFileRead(fileNameLoc)
% dopOSCCI Mark II: dopBehFileRead ~ 16-11-2010 (last edit)
%
% read dopOSCCI behavioural file: a tab delimitted file with first column
% of file names (could be full path - file name location) and then a series
% of columns (number of epochs) labelled with respect to the behavioural
% variable, e.g., 'cond' and epoch number:
% 'condEpoch1' (tab) 'condEpoch2' (tab) 'condEpoch3' (tab) etc.
%

% -------------------------------------------------------------------------
%     '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\t%s\n',['Running ',mfilename],...
    'Reading dopOSCCI behavioural file:');
try
    if iscell(fileNameLoc)
        fileNameLoc=fileNameLoc{1};
    end
    [dbr.tmp.fl dbr.tmp.fn dbr.tmp.fext]=fileparts(fileNameLoc);
    if exist(fileNameLoc,'file')==2 && strcmp(dbr.tmp.fext,'.txt')
        dbr.fileNameLoc=fileNameLoc;%dtd.stitchFile;
        dbr.out.okay=0;
        dbr.translation='dopOSCCI behavioural read';
        dbr.abbreviation='dbr'; % useful for debugging
        
        %% import the stitchFile
        dbr.im=importdata(dbr.fileNameLoc); % imported data
        % something like:
        %          data: [8x24 double]
        %     textdata: {9x25 cell}
        dbr.dataSize=size(dbr.im.data);
        dbr.textSize=size(dbr.im.textdata);
        dbr.out.n=dbr.textSize(1)-1; % number of rows (people) minus column header row
        
        %% file names
        i=1;% skip the first row = column header
        dbr.out.list=[];
        while i<dbr.textSize(1); i=i+1;
            dbr.out.list{end+1}=dbr.im.textdata{i};
        end
        
        %% headers
        i=0;
        dbr.headers=[]; % ignores first header (should be file names anyway)
        while ((i+1)*dbr.textSize(1)+1)<prod(dbr.textSize); i=i+1;
            dbr.headers{end+1}=dbr.im.textdata{i*dbr.textSize(1)+1};
        end
        
        %% find behavioural variables
        % using length(cellfun('size',dbr.out.varNames,1)) to determine how
        % many cells are in the array... might be a better way but
        % currently I'm finding when there is a single cell in the array
        % then the size(X,2) or length(X) functions return the number of
        % characters which isn't helpful...
        i=0;
        dbr.out.varNames=[];
        dbr.out.epochs=[];
        dbr.out.varRange=[];
        dbr.repText=[];
        dbr.reportForm='%s '; % use this for output report below
        while i<length(dbr.headers); i=i+1;
            dbr.tmp.hd=dbr.headers{i}; % header
            if strfind(dbr.tmp.hd,'Epoch')
                dbr.tmp.vn=dbr.tmp.hd(1:strfind(dbr.tmp.hd,'Epoch')-1) ; % variable name
                if ~sum(strcmp(dbr.tmp.vn,dbr.out.varNames))
                    dbr.out.varNames{end+1}=dbr.tmp.vn;
                    dbr.repText{end+1}=dbr.out.varNames{end};
                    dbr.reportForm=[dbr.reportForm,'%s\t'];
                    if length(cellfun('size',dbr.out.varNames,1))>1 && ...
                            size(dbr.out.varRange,1)<length(cellfun('size',dbr.out.varNames,1))
                        % new variable
                        dbr.out.varRange(length(cellfun('size',dbr.out.varNames,1))-1,2)=i-1;
                    end
                    dbr.out.varRange(length(cellfun('size',dbr.out.varNames,1)),1)=i;
                end
            end
        end
        if ~isempty(dbr.out.varRange)
            dbr.out.varRange(length(cellfun('size',dbr.out.varNames,1)),2)=i;
            for i=1:length(cellfun('size',dbr.out.varNames,1))
                dbr.out.epochs(i)=1+dbr.out.varRange(i,2)-dbr.out.varRange(i,1);
            end
        end
        if ~isempty(dbr.out.varNames) && ~isempty(dbr.out.varRange)
            dbr.out.okay=1;
            dbr.out.nVar=length(cellfun('size',dbr.out.varNames,1));
        end
        %% sort data
        % put data into variable labelled data array
        dbr.out.levels=[]; % number of levels per
        
        if dbr.out.okay
            for i=1:length(cellfun('size',dbr.out.varNames,1))
                if dbr.out.varRange(i,2)<=dbr.dataSize(2)
                    dbr.out.data.(dbr.out.varNames{i})=...
                        dbr.im.data(:,dbr.out.varRange(i,1):dbr.out.varRange(i,2));
                    dbr.out.levels.(dbr.out.varNames{i})=unique(dbr.out.data.(dbr.out.varNames{i}))';
                    dbr.repText{i}=[dbr.out.varNames{i},' (',num2str(dbr.out.levels.(dbr.out.varNames{i})),')'];
                else
                    % can't see how this would ever happen
                    fprintf('\t%s\n',['Not enough data for ',dbr.out.varNames{i}]);
                end
            end
        end
        %% report
        dbr.out.guiReport=sprintf('%s\n',...
            sprintf(dbr.reportForm,[num2str(dbr.out.nVar),' variables found: '],dbr.repText{1:end}));
        dbr.out.report=sprintf('%s\n\t%s\n\t%s\n\t%s\n',...
            ['Behavioural File Report: ',dbr.fileNameLoc],...
            [num2str(dbr.out.nVar),' variables found'],...
            sprintf(dbr.reportForm,'Behavioural Variables = ',dbr.repText{1:end}),...
            ['n = ',num2str(dbr.out.n),' individual series']);
        disp(dbr.out.report);
    else
        fprintf('%s\n\t%s\n\n%s\n','Behavioural file was NOT found:',...
            fileNameLoc,'Therefore, behavioural file can''t be read...');
        dbr.out.okay=0;
    end
    %% set output
    varargout{1}=dbr.out;
    clear dsr
catch err
    %% catch dopOSCCI error
    save(dopOSCCIdebug(mfilename));throw(err);
end