% Pattern Object: Contrast-Images (according to specification of SPM.mat)
%   pattern init by extracting pathes of con-Files
classdef janis_patternCon < janis_patternAbstractImg

   properties (SetAccess = public)
      ImgType = 'contrast';
   end

    methods
      %Constructor:
      % gets an SPM file and a list of conditions, which must match the
      % condition of con files in the SPM.mat
      function obj = janis_patternCon(SPMfile,listOfConditions)
            obj = obj@janis_patternAbstractImg;
            if nargin > 0
              obj.SPMfile = SPMfile;
              obj = addCondition(obj,SPMfile,listOfConditions);
            end
      end

        function obj = addCondition(obj,SPMfile,listOfConditions)
            obj.SPMfile = SPMfile;
            try
                load(SPMfile);
            catch excep
             fprintf('Unable to access spm.mat: %s\n', SPMfile);
             rethrow(excep);
            end
            try
                conNames = {SPM.xCon.Vcon};
                conNames = cell2mat(conNames);
                conNames = {conNames.descrip};
                for condCount =1:size(listOfConditions,1)
                    % find Index of Condition
                    conIdx = strcmpi(conNames,listOfConditions{condCount});
                    if exist(SPM.xCon(conIdx).Vcon.fname)
                        obj = obj.addImage(SPM.xCon(conIdx).Vcon.fname);
                    elseif exist([SPM.swd filesep SPM.xCon(conIdx).Vcon.fname])
                        obj = obj.addImage([SPM.swd filesep SPM.xCon(conIdx).Vcon.fname]);
                    elseif exist(SPM.xCon(conIdx).Vcon.descrip)
                        obj = obj.addImage(SPM.xCon(conIdx).Vcon.descrip);
                    else
                        throw(MException('janis:ConFileNotFound','Could not parse confile from SPM.mat'));
                    end
                end
            catch excep
                % exception handlig if no con found
                error('Unable to find all con-images for subject: %s',SPMfile);
                rethrow(excep);
            end
        end
    end

end