% A pattern which gets image locations for initialization
% e.g. for T1 images or for beta-images if no spm-file is available.
%
% create new pattern with:
%       janis_patternSimple(listOfImages)
% ... where ´listOfImages´ is a cellarray containing pathes to files:
%       *.img,
%       *.nii, or
%       *.hdr
%
classdef janis_patternSimple < janis_pattern

   properties (SetAccess = public)
       ImgType = 'image simple';
   end

   properties (SetAccess = protected)
      imgFiles;             % list of image files
   end

  methods


    %Constructor:
    function obj = janis_patternSimple(listOfImages)
        obj = obj@janis_pattern;
        if nargin>0
            for imgCount =1:numel(listOfImages)
                try
                    obj = obj.addImage(listOfImages{imgCount});
                catch excep
                % exception handlig if no image found
                    error('Unable to find image: %s',listOfImages{imgCount});
                    rethrow(excep);
                end
            end
        end
    end

    function newJp = copy(this)
       newJp = copy@janis_pattern(this);
       newJp.imgFiles = this.imgFiles;
    end

    % adds a new image
    function this = addImage(this,image)
        this.imgFiles{size(this.imgFiles,2)+1} = image;
    end

    % generate pattern, i.e. load the images using
    %       spm_read_vol()  and
    %       spm_vol()
    function this = generatePattern(this)
        for imgCount=1:numel(this.imgFiles)
            if ~isempty(this.imgFiles{imgCount})
                try
                    images{imgCount} = spm_read_vols(spm_vol(this.imgFiles{imgCount}));
                catch excep
                    error('Loading image failed: %s', this.imgFiles{imgCount});
                    rethrow(excep);
                end
            end
        end
        this.sourceDimension = cellfun(@(x) size(x),images,'UniformOutput',false);
        fs = getFeatureSelection(this);
        images = fs.reduce(images{:});
        if ~isempty(images)
            this.VoxelValues = images;
            this.isLoaded = true;
        else
            warning('janis:emptyImg','Image was empty, something went wrong');
            this.isLoaded = false;
        end
    end

    function this = freePattern(this)
       this.VoxelValues = [];
       this.isLoaded = false;
    end

    function markers = getUniqueMarkers(this,markers)
        markers.imgFiles = this.imgFiles;
    end
  end
end