function varargout = ica_orth_views(file,mat,varargin)
%% Orthogonal viewer



tic;
h=waitbar(0,'please waiting...');
file=file(1,:);
mat=mat(1,:);
image_values = 'positive and negative';
cmap = [];
threshold = 0;
convert_to_zscores = 'no';
coords = [0, 0, 0];
structFile = '';
isInteractive = 1;
set_to_max_voxel = 0;
fig_title = 'OrthoViews';
returnInterpdata = 0;
index=1;
 [dd, FileName, extn] = fileparts(deblank(file(1,:)));

fig_title=FileName;
 


%% Loop over variable no. of arguments
for n = 1:2:length(varargin)
    if (strcmpi(varargin{n}, 'structfile'))
        structFile = varargin{n + 1};
    elseif (strcmpi(varargin{n}, 'coords'))
        coords = varargin{n + 1};
    elseif (strcmpi(varargin{n}, 'image_values'))
        image_values = varargin{n + 1};
    elseif (strcmpi(varargin{n}, 'cmap'))
        cmap = varargin{n + 1};
    elseif (strcmpi(varargin{n}, 'threshold'))
        threshold = varargin{n + 1};
    elseif (strcmpi(varargin{n}, 'convert_to_zscores'))
        convert_to_zscores = varargin{n + 1};
    elseif (strcmpi(varargin{n}, 'labels'))
        labels = varargin{n + 1};
    elseif (strcmpi(varargin{n}, 'isinteractive'))
        isInteractive = varargin{n + 1};
    elseif (strcmpi(varargin{n}, 'fig_title'))
        fig_title = varargin{n + 1};
    elseif (strcmpi(varargin{n}, 'tc'))
        tc = varargin{n + 1};
    elseif (strcmpi(varargin{n}, 'set_to_max_voxel'))
        set_to_max_voxel = varargin{n + 1};
    elseif (strcmpi(varargin{n}, 'get_interp_data'))
        returnInterpdata = varargin{n + 1};
    elseif (strcmpi(varargin{n}, 'position'))
        fig_pos = varargin{n + 1};
    elseif (strcmpi(varargin{n}, 'fnamelist'))
        fnamelist=varargin{n + 1};
    elseif (strcmpi(varargin{n}, 'matlist'))
        matlist=varargin{n + 1}; 
    elseif (strcmpi(varargin{n}, 'template'))%template path
        template=varargin{n + 1}; 
    elseif (strcmpi(varargin{n}, 'tempNum'))
        tempNum=varargin{n + 1}; %templatenum
    elseif (strcmpi(varargin{n}, 'templatelist'))
        templatelist=varargin{n + 1};
    elseif (strcmpi(varargin{n}, 'temp'))
        temp=varargin{n + 1};
    end
    
        
end
% for i=1:length(templatelist)
%     temp_list(i).path=strcat(templatelist(i).folder,filesep,templatelist(i).name);
% end



v0=spm_vol(template);%user input .nii
aalData=spm_read_vols(v0); 
fprintf('Calculating related regions....\n')
if ishandle(h)
    waitbar(1/3,h,'Calculating related regions ... ');
end

region=calcuRegion(file,aalData,template,tempNum);
templateregion=calcuRegion(temp,aalData,template,tempNum);
tempfile=temp;
if (length(coords) == numel(coords))
    coords = coords(:)';
end

if (size(coords, 2) ~= 3)
    error('No. of columns of coords is not equal to 3. coords must contain x,y,z coordsinates');
end

% Turn off interactive if multiple coordsinates are plotted
if (length(coords) ~= numel(coords))
    isInteractive = 0;
end

if (~exist('labels', 'var'))
    labels = repmat({''}, 1, size(coords, 1));
end

labels = cellstr(labels);
convertToZ = strcmpi(convert_to_zscores, 'yes');

returnValue = 1;
%% Interpolate selected image to structural dimensions. Get the interactive
%% input?
[pathstr, file, extn] = fileparts(file);
if isempty(pathstr)
    pathstr = pwd;
end

file = fullfile(pathstr, [file, extn]);

if (~isempty(structFile))
    if (ischar(structFile))
        [pathstr, structFile, extn] = fileparts(structFile);
        if isempty(pathstr)
            pathstr = pwd;
        end
        structFile = fullfile(pathstr, [structFile, extn]);
    end
else
    structFile = file;
end

[structFile, n] = ica_parseExtn(structFile);
structVol = spm_vol_nifti(structFile, n);
structVol = structVol(1);

[images, real_world_coords] = ica_resizeImage(structVol, file, 'axial', [], 1);
[templateimages, real_world_coords2] = ica_resizeImage(structVol, tempfile, 'axial', [], 1);
data = reshape(images(2, :, :, :), [size(images, 2), size(images, 3), size(images, 4)]);
tempdata=reshape(templateimages(2, :, :, :), [size(templateimages, 2), size(templateimages, 3), size(templateimages, 4)]);
structData = reshape(images(1, :, :, :), [size(images, 2), size(images, 3), size(images, 4)]);
clear images;
clear templateimages;
stdData = 1;
meanData = 0;
if (convertToZ)
    meanData = mean(data(data~=0));
    stdData = std(data(data~=0));
    data(data~=0) =  (data(data ~= 0) - meanData)/stdData;
    
    tempmeanData = mean(tempdata(tempdata~=0));
    tempstdData = std(tempdata(tempdata~=0));
    tempdata(tempdata~=0) =  (tempdata(tempdata ~= 0) - tempmeanData)/tempstdData;
    
end

data = applyDispParams(data, returnValue, threshold);
tempdata=applyDispParams(tempdata, returnValue, threshold);

tempgood_inds = find(abs(tempdata) > eps);

good_inds = find(abs(data) > eps);

minICAIM = min(data(good_inds));
maxICAIM = max(data(good_inds));

tempminICAIM = min(tempdata(tempgood_inds));
tempmaxICAIM = max(tempdata(tempgood_inds));
tempmaxICAIM = max([tempmaxICAIM, abs(threshold)]);

maxICAIM = max([maxICAIM, abs(threshold)]);

if (isempty(minICAIM))
    minICAIM = eps;
end
if (isempty(tempminICAIM))
    tempminICAIM = eps;
end


if (isempty(maxICAIM))
    maxICAIM = eps;
end
if (isempty(tempmaxICAIM))
    tempmaxICAIM = eps;
end

if (returnValue == 1)
    maxICAIM = max(abs([minICAIM, maxICAIM]));
    minICAIM = -maxICAIM;
end

if (returnValue == 1)
    tempmaxICAIM = max(abs([tempminICAIM, tempmaxICAIM]));
    tempminICAIM = -tempmaxICAIM;
end

dataRange = [minICAIM, maxICAIM];
tempdataRange=[tempminICAIM, tempmaxICAIM];
[dd, inds] = max(abs(data(:)));
[tempdd, tempinds] = max(abs(tempdata(:)));
[x, y, z] = ind2sub(size(data), inds);
[tempx, tempy, tempz] = ind2sub(size(tempdata), tempinds);
maxVoxelPos = squeeze(real_world_coords(x, y, z, :))';
tempmaxVoxelPos = squeeze(real_world_coords2(tempx, tempy, tempz, :))';
if (~set_to_max_voxel)
    pixelPos = round(ica_real_to_voxel(structVol, coords(1, :)));
else
    pixelPos = [x, y, z];
end

if (~set_to_max_voxel)
    temppixelPos = round(ica_real_to_voxel(structVol, coords(1, :)));
else
    temppixelPos = [tempx, tempy, tempz];
end



maxICAIM = round(maxICAIM*10)/10;
minICAIM = round(minICAIM*10)/10;

minInterval = 0;
maxInterval = 100;


tempmaxICAIM = round(tempmaxICAIM*10)/10;
tempminICAIM = round(tempminICAIM*10)/10;
 

%% Get colormap associated with the image values
 cmap = [cmap; gray(size(cmap, 1))];

CLIM = [minInterval, 2*maxInterval];
tempCLIM=[minInterval, 2*maxInterval];
if (returnInterpdata)
    composite_data = getCompositeData(structData, data, returnValue, minInterval, maxInterval, dataRange);
    handles_data.data = composite_data;
    tempcomposite_data = getCompositeData(structData, tempdata, returnValue, minInterval, maxInterval, tempdataRange);
    handles_data.tempdata = tempcomposite_data;
    
else
    handles_data.dispPrefs = struct('returnValue', returnValue, 'stdData', stdData, 'meanData', meanData, 'imgVol', ...
        ica_returnHInfo(file), 'threshold', threshold);
    handles_data.tempdispPrefs = struct('returnValue', returnValue, 'stdData', tempstdData, 'meanData', tempmeanData, 'imgVol', ...
        ica_returnHInfo(tempfile), 'threshold', threshold);
end
handles_data.file = file;
handles_data.tempfile = tempfile;

handles_data.CLIM = CLIM;
handles_data.tempCLIM = tempCLIM;

handles_data.range = dataRange;
handles_data.temprange = tempdataRange;

handles_data.minInterval = minInterval;

handles_data.maxInterval = maxInterval;

handles_data.pixelPos = pixelPos;
handles_data.temppixelPos = temppixelPos;

handles_data.coords = coords;
handles_data.origin = [0, 0, 0];
handles_data.voxelOrigin = ica_real_to_voxel(structVol(1), handles_data.origin);
handles_data.VOX = abs([structVol(1).mat(1, 1), structVol(1).mat(2, 2), structVol(1).mat(3, 3)]);
handles_data.structVol = structVol;

handles_data.minICAIM = minICAIM;
handles_data.maxICAIM = maxICAIM;

handles_data.tempminICAIM = tempminICAIM;
handles_data.tempmaxICAIM = tempmaxICAIM;

handles_data.labels = labels;

handles_data.maxVoxelPos = maxVoxelPos;
handles_data.tempmaxVoxelPos = tempmaxVoxelPos;

handles_data.isInteractive = isInteractive;
handles_data.cmap = cmap;
handles_data.matname=mat;
handles_data.fnamelist=fnamelist;
handles_data.matlist=matlist;
handles_data.templatelist=templatelist;
handles_data.index=index;
handles_data.template=template;
handles_data.region=region;
handles_data.templateregion=templateregion;
handles_data.aalData=aalData;
handles_data.tempNum=tempNum;
if (returnInterpdata)
    handles_data.maxVoxelPos = handles_data.pixelPos;
    varargout{1} = handles_data;
    return;
end

if exist('tc', 'var')
    handles_data.numRowsToPlot = (size(coords, 1) + 1);
else
    handles_data.numRowsToPlot = (size(coords, 1));
end

%% Figure and Menus
gH =ica_getGraphics(fig_title, 'graphics', 'orthoviews', 'off');

set(0,'currentfigure',gH);
if (exist('fig_pos', 'var'))
    set(gH, 'position', fig_pos);
end

if (isInteractive)
    cmenu = uicontextmenu;
    set(gH, 'UIContextMenu', cmenu);
    uimenu(cmenu, 'Label', 'Set Voxel Position (mm)', 'Callback', {@setVoxelPos, gH});
    maxVoxelH = uimenu(cmenu, 'Label', 'Go To Max Voxel', 'Callback', {@setMaxVoxel, gH});
end

colormap(cmap);
gHpos=get(gH,'position');
left1=gHpos(3)/4-70/2;
left2=gHpos(3)/4-70/2+gHpos(3)/2;
buttonPosition1=[left1,10 70 30];
buttonPosition2=[left2,10 70 30];
previous=uicontrol('parent',gH,'style','pushbutton','position',buttonPosition1,'string','Back', 'ForegroundColor',[0 0 0],'fontsize',10);
next=uicontrol('parent',gH,'style','pushbutton','position',buttonPosition2,'string','Next', 'ForegroundColor',[0 0 0],'fontsize',10);


handles_data.currentFigure = gH;
 
handles_data.next=next;
handles_data.previous=previous;
set(gH, 'userdata', handles_data);


set(previous, 'callback', {@previousCallback, gH});
set(next, 'callback', {@nextCallback, gH});
fprintf('Drawing slices...\n')
if ishandle(h)
    waitbar(2/3,h,'Drawing slices... ');
end
set(0,'currentfigure',gH);
drawSlices(handles_data);

if (set_to_max_voxel)
    setMaxVoxel(maxVoxelH, [], gH);
end 

fprintf('Displaying title and realted region...\n')
if ishandle(h)
    waitbar(1,h,'Displaying title and realted region... ');
end
set(0,'currentfigure',gH);

axisH = axes('Parent', gH, 'position', [0 0 1 1], 'visible', 'off','tag','title');
xPos = 0.5; yPos = 0.94;
titleColor = 'c';
text(xPos, yPos, fig_title, 'color', titleColor, 'fontweight', 'bold', 'fontsize', 12 + 1, 'HorizontalAlignment', 'center', 'FontName', 'times', 'parent', axisH,'hittest','off');

atlasX=0;atlasY=0.98;
atlasColor=[0 0 0];
text(atlasX,atlasY,region, 'color', atlasColor, 'fontweight', 'bold', 'fontsize', 10, 'HorizontalAlignment', 'left', 'FontName', 'times', 'parent', axisH,'hittest','off',...
        'backgroundcolor',[1 1 1]);

cb2pos=get(findobj(gH, 'tag', 'compviewerColorbar'),'position');
text(atlasX,cb2pos(2)-0.01,templateregion, 'color', atlasColor, 'fontweight', 'bold', 'fontsize', 10, 'HorizontalAlignment', 'left', 'FontName', 'times', 'parent', axisH,'hittest','off',...
        'backgroundcolor',[1 1 1]);
   yPos2=cb2pos(2)-0.02;
% text(xPos, yPos2, ['ICnum',num2str(index)], 'color', titleColor, 'fontweight', 'bold', 'fontsize', 12 + 1, 'HorizontalAlignment', 'center', 'FontName', 'times', 'parent', axisH,'hittest','off');
 [dd, FileName, extn] = fileparts(deblank(templatelist(index,:)));
     temp_title=FileName;
% text(xPos, yPos2, ['ICnum',num2str(index)], 'color', titleColor, 'fontweight', 'bold', 'fontsize', 12 + 1, 'HorizontalAlignment', 'center', 'FontName', 'times', 'parent', axisH,'hittest','off');
text(xPos, yPos2,temp_title , 'color', titleColor, 'fontweight', 'bold', 'fontsize', 12 + 1, 'HorizontalAlignment', 'center', 'FontName', 'times', 'parent', axisH,'hittest','off');
         
set(gH, 'visible', 'on');
drawnow;

if (nargout == 1)
    varargout{1} = gH;
end
if ishandle(h)
    delete(h);
end
fprintf('Complete! \n')
toc;
function handles_data= drawSlices(handles_data)
%% Draw Slices
%
 
FONT_COLOR=[1 1 1];

CLIM = handles_data.CLIM;
tempCLIM=handles_data.tempCLIM;
minInterval = handles_data.minInterval;
maxInterval = handles_data.maxInterval;
coords = handles_data.coords;
% structVol = handles_data.structVol;
labels = handles_data.labels;
minICAIM = handles_data.minICAIM;
maxICAIM = handles_data.maxICAIM;

tempminICAIM = handles_data.tempminICAIM;
tempmaxICAIM = handles_data.tempmaxICAIM;

gH = handles_data.currentFigure;
% matname= handles_data.matname;
matlist=handles_data.matlist;
allAxes = zeros(numel(coords), 1);
allAxes2 = zeros(numel(coords), 1);
index=handles_data.index;
% region=handles_data.region;
countA = 0;
 
for ncoords = 1:size(coords, 1)
    
    realCoords = coords(ncoords, :);

    [sliceXY, sliceXZ, sliceYZ] = returnSlices(handles_data, realCoords);
    
    countA = countA + 1;
%     sh = subplot( handles_data.numRowsToPlot, 3, countA);
    sh = subplot( 3, 3, countA);
    set(sh, 'units', 'normalized');
    plotImage(sh, sliceYZ, CLIM);
    xlabel(['X = ', num2str(realCoords(1)), ' mm'], 'parent', sh);
    firstPos = get(sh, 'position');
    allAxes(countA) = sh;
    
    sh = subplot( 3, 3, 4);
    set(sh, 'units', 'normalized');
    plotImage(sh, sliceYZ, tempCLIM);
    xlabel(['X = ', num2str(realCoords(1)), ' mm'], 'parent', sh);
    firstPos2 = get(sh, 'position');
    allAxes2(1) = sh;
    
    
    countA = countA + 1;
%     sh = subplot( handles_data.numRowsToPlot, 3, countA);
    sh = subplot( 3, 3, countA);
    set(sh, 'units', 'normalized');
    plotImage(sh, sliceXZ, CLIM);
    xlabel(['Y = ', num2str(realCoords(2)), ' mm'], 'parent', sh);
    middleAxes = sh;
    allAxes(countA) = sh;
    
    sh = subplot( 3, 3, 5);
    set(sh, 'units', 'normalized');
    plotImage(sh, sliceXZ, tempCLIM);
    xlabel(['Y = ', num2str(realCoords(2)), ' mm'], 'parent', sh);
    middleAxes2 = sh;
    allAxes2(2) = sh;
    
    
    countA = countA + 1;
%     sh = subplot( handles_data.numRowsToPlot, 3, countA);
    sh = subplot( 3, 3, countA);
    set(sh, 'units', 'normalized');
    plotImage(sh, sliceXY, CLIM);
    xlabel(['Z = ', num2str(realCoords(3)), ' mm'], 'parent', sh);
    lastPos = get(sh, 'position');
    allAxes(countA) = sh;
    
    sh = subplot( 3, 3, 6);
    set(sh, 'units', 'normalized');
    plotImage(sh, sliceXY, tempCLIM);
    xlabel(['Z = ', num2str(realCoords(3)), ' mm'], 'parent', sh);
    lastPos2 = get(sh, 'position');
    allAxes2(3) = sh;
    
    % Plot label
    title(labels{ncoords}, 'parent', middleAxes);
    width = lastPos(1) + lastPos(3) - firstPos(1);
   
    
    % Plot horizontal colorbar
    if (ncoords == size(coords, 1))
        colorBarWidth = 0.3;
        colorBarHeight = 0.016;
        pos = [firstPos(1) + width/2 - colorBarWidth/2, lastPos(2) - 0.08, colorBarWidth, colorBarHeight];
        ch = colorbar('horiz');
        set(ch, 'units', 'normalized');
        set(ch, 'tag', 'compviewerColorbar');
        set(ch, 'position', pos);
        %ch = colorbar(pos);
        set(ch, 'xLim', [minInterval, maxInterval]);
        xTicks = get(ch, 'xTick');
        set(ch, 'yTick', []);
        set(ch, 'xTick', [xTicks(1), xTicks(end)]);
        set(ch, 'xTicklabel', cellstr(num2str([minICAIM;maxICAIM])));
        set(ch, 'XColor', FONT_COLOR, 'YColor', FONT_COLOR);
        %set(ch, 'tag', 'colorbar');
        set(ch, 'units', 'normalized');
        handles_data.ch = ch;
    end
    
    if (ncoords == size(coords, 1))
        colorBarWidth = 0.3;
        colorBarHeight = 0.016;
        pos = [firstPos2(1) + width/2 - colorBarWidth/2, lastPos2(2) - 0.06, colorBarWidth, colorBarHeight];
        ch2 = colorbar('horiz');
        set(ch2, 'units', 'normalized');
        set(ch2, 'tag', 'compviewerColorbar2');
        set(ch2, 'position', pos);
        %ch = colorbar(pos);
        set(ch2, 'xLim', [minInterval, maxInterval]);
        xTicks = get(ch2, 'xTick');
        set(ch2, 'yTick', []);
        set(ch2, 'xTick', [xTicks(1), xTicks(end)]);
        set(ch2, 'xTicklabel', cellstr(num2str([tempminICAIM;tempmaxICAIM])));
        set(ch2, 'XColor', FONT_COLOR, 'YColor', FONT_COLOR);
        %set(ch, 'tag', 'colorbar');
        set(ch2, 'units', 'normalized');
        handles_data.ch2 = ch2;
    end
    
    
    
    
    
end

set(allAxes, 'XColor', get(gH, 'color'), 'YColor', get(gH, 'color'));
set(allAxes2, 'XColor', get(gH, 'color'), 'YColor', get(gH, 'color'));
xlabelH = get(allAxes, 'XLabel');
xlabelH2 = get(allAxes2, 'XLabel');
childAxesH = get(findobj(gH, 'Type', 'Axes'), 'children');
if length(childAxesH)==7
    childAxesH(7)='';
end
 

for nX = 1:length(xlabelH)
    if (iscell(xlabelH))
        set(xlabelH{nX}, 'color', FONT_COLOR);
    else
        set(xlabelH(nX), 'color', FONT_COLOR);
    end
end

for nX = 1:length(xlabelH2)
    if (iscell(xlabelH2))
        set(xlabelH2{nX}, 'color', FONT_COLOR);
    else
        set(xlabelH2(nX), 'color', FONT_COLOR);
    end
end

load(strtrim(matlist(index,:)));
 
timepoints=length(a);
x=1:timepoints;
b=a(:,1);
sh=subplot(3,1,3);

plot(x,b','-ob');
grid on;
set(sh,'xcolor',[1 1 1]);
set(sh,'ycolor',[1 1 1]);
set(sh,'color',[1 1 1]);
set(sh,'units','pixels');
%  
%  legend('Time Course','textcolor',[0 0 0]);
title('Time Course');
if (handles_data.isInteractive)
    for nX = 1:length(childAxesH)
        set(childAxesH{nX}, 'hittest', 'off');
    end
    %set(childAxesH, 'hittest', 'off');
    set(allAxes(1), 'ButtonDownFcn', {@quad1Callback, gH});
    set(allAxes(2), 'ButtonDownFcn', {@quad2Callback, gH});
    set(allAxes(3), 'ButtonDownFcn', {@quad3Callback, gH});
    
    set(allAxes2(1), 'ButtonDownFcn', {@quad1Callback, gH});
    set(allAxes2(2), 'ButtonDownFcn', {@quad2Callback, gH});
    set(allAxes2(3), 'ButtonDownFcn', {@quad3Callback, gH});
end
%button
handles_data.allAxes = allAxes;
handles_data.allAxes2 = allAxes2;
% region=handles_data.region;
set(gH, 'userdata', handles_data);
 
set(findobj(gH, 'tag', 'compviewerColorbar'), 'xLim', [minInterval, maxInterval]);
 
set(findobj(gH, 'tag', 'compviewerColorbar2'), 'xLim', [minInterval, maxInterval]);
% set(findobj(0, 'tag', 'aalname'),'string',region);

drawnow;

set(gH, 'visible', 'on');



function nextCallback(hObject, event_data, handles)
    tic;
     h=waitbar(0,'please waiting...');
    fprintf('Please waiting.......\n');
    
    handles_data = get(handles, 'userdata');
    set(handles_data.previous,'enable','off');
    set(handles_data.next,'enable','off');
    currentIndex=handles_data.index;
    fnamelist=handles_data.fnamelist;
    matlist=handles_data.matlist;
    templatelist=handles_data.templatelist;
    template=handles_data.template;
    tempNum=handles_data.tempNum;
%     maxVoxelH=handles_data.maxVoxelH;
     
    % 
    gH=handles_data.currentFigure;
    set(0,'currentfigure',gH);
    if currentIndex<size(fnamelist,1)
        index=currentIndex+1;
    else
        index=1;
    end
    
    handles_data.index=index;
    fprintf('Calculating related region....\n');
    if ishandle(h)
         waitbar(1/3,h,'Calculating related region... ');
    end  
    
    handles_data=toggleImage(index,matlist,fnamelist,handles_data);
    aalData=handles_data.aalData;

    ic=fnamelist(index,:);
    tempic=templatelist(index,:);
       
     
    region= calcuRegion(ic,aalData,template,tempNum);
    templateregion=calcuRegion(tempic,aalData,template,tempNum);
    handles_data.region=region;
    handles_data.templateregion=templateregion;
    
    handles_data.coords = handles_data.maxVoxelPos;
    handles_data.pixelPos = round(handles_data.voxelOrigin + (handles_data.coords./handles_data.VOX));

    set(handles, 'userdata', handles_data);
    
   fprintf('Drawing slices...\n');
    if ishandle(h)
        waitbar(2/3,h,'Drawing slices... ');
    end
    set(0,'currentfigure',gH);
     
    handles_data=drawSlices(handles_data);
    updateSlices(handles_data);
     
    
     if ishandle(h)
        waitbar(1,h,'Displaying title and realted region... ');
    end
     set(0,'currentfigure',gH);
    
    [dd, FileName, extn] = fileparts(deblank(fnamelist(index,:)));
    fig_title=FileName;
     
    axisH = axes('Parent', gH, 'position', [0 0 1 1], 'visible', 'off','tag','title');
    xPos = 0.5; yPos = 0.94;
    titleColor = 'c';
    text(xPos, yPos, fig_title, 'color', titleColor, 'fontweight', 'bold', 'fontsize', 12 + 1, 'HorizontalAlignment', 'center', 'FontName', 'times', 'parent', axisH,'hittest','off');
     
    

   
    
    atlasX=0;atlasY=0.98;
    atlasColor=[0 0 0];
    text(atlasX,atlasY,region, 'color', atlasColor, 'fontweight', 'bold', 'fontsize', 10, 'HorizontalAlignment', 'left', 'FontName', 'times', 'parent', axisH,'hittest','off',...
        'backgroundcolor',[1 1 1]);

    cb2pos=get(findobj(gH, 'tag', 'compviewerColorbar'),'position');
    text(atlasX,cb2pos(2)-0.01,templateregion, 'color', atlasColor, 'fontweight', 'bold', 'fontsize', 10, 'HorizontalAlignment', 'left', 'FontName', 'times', 'parent', axisH,'hittest','off',...
        'backgroundcolor',[1 1 1]);
    yPos2=cb2pos(2)-0.02;
    
     [dd, FileName, extn] = fileparts(deblank(templatelist(index,:)));
     temp_title=FileName;
% text(xPos, yPos2, ['ICnum',num2str(index)], 'color', titleColor, 'fontweight', 'bold', 'fontsize', 12 + 1, 'HorizontalAlignment', 'center', 'FontName', 'times', 'parent', axisH,'hittest','off');
text(xPos, yPos2,temp_title , 'color', titleColor, 'fontweight', 'bold', 'fontsize', 12 + 1, 'HorizontalAlignment', 'center', 'FontName', 'times', 'parent', axisH,'hittest','off');
    
        
    set(gH,'name',fig_title);
    set(handles_data.previous,'enable','on');
    set(handles_data.next,'enable','on');
    fprintf('New component is done!\n');
    toc;
    if ishandle(h)
        delete(h);
    end
  
 
function previousCallback(hObject, event_data, handles)
    tic;
%1.create
% iscanceled=false;
h=waitbar(0,'please waiting...');
%  btncancel=findall(h,'style','pushbutton');
%  set(btncancel,'string','Cancel','fontsize',10);
    
fprintf('please waiting.......\n');
handles_data = get(handles, 'userdata');
currentIndex=handles_data.index;
fnamelist=handles_data.fnamelist;
templatelist=handles_data.templatelist
matlist=handles_data.matlist;
aalData=handles_data.aalData;
template=handles_data.template;
tempNum=handles_data.tempNum;
set(handles_data.next,'enable','off');
set(handles_data.previous,'enable','off');
% 
gH=handles_data.currentFigure;
  
if currentIndex>1
    index=currentIndex-1;
else
    index=size(fnamelist,1);
end

handles_data.index=index;
fprintf('Calculating related region....\n');
if ishandle(h)
     waitbar(1/3,h,'Calculating related region... ');
end
handles_data=toggleImage(index,matlist,fnamelist,handles_data);
ic=fnamelist(index,:);
tempic=templatelist(index,:);
       
     
region= calcuRegion(ic,aalData,template,tempNum);
templateregion=calcuRegion(tempic,aalData,template,tempNum);
handles_data.region=region;
handles_data.templateregion=templateregion;

 

handles_data.coords = handles_data.maxVoxelPos;
handles_data.pixelPos = round(handles_data.voxelOrigin + (handles_data.coords./handles_data.VOX));
 
set(handles, 'userdata', handles_data);
fprintf('Drawing slices...\n');
if ishandle(h)
    waitbar(2/3,h,'Drawing slices... ');
end
set(0,'currentfigure',gH);
handles_data=drawSlices(handles_data);
updateSlices(handles_data);

 
 if ishandle(h)
    waitbar(1,h,'Displaying title and realted region... ');
end
 set(0,'currentfigure',gH);
[dd, FileName, extn] = fileparts(deblank(fnamelist(index,:)));
fig_title=FileName;
 axisH = axes('Parent', gH, 'position', [0 0 1 1], 'visible', 'off','tag','title');
xPos = 0.5; yPos = 0.94;
titleColor = 'c';
text(xPos, yPos, fig_title, 'color', titleColor, 'fontweight', 'bold', 'fontsize', 12 + 1, 'HorizontalAlignment', 'center', 'FontName', 'times', 'parent', axisH,'hittest','off');
  

atlasX=0;atlasY=0.98;
atlasColor=[0 0 0];
text(atlasX,atlasY,region, 'color', atlasColor, 'fontweight', 'bold', 'fontsize', 10, 'HorizontalAlignment', 'left', 'FontName', 'times', 'parent', axisH,'hittest','off',...
        'backgroundcolor',[1 1 1]);
    
 cb2pos=get(findobj(gH, 'tag', 'compviewerColorbar'),'position');
    text(atlasX,cb2pos(2)-0.01,templateregion, 'color', atlasColor, 'fontweight', 'bold', 'fontsize', 10, 'HorizontalAlignment', 'left', 'FontName', 'times', 'parent', axisH,'hittest','off',...
        'backgroundcolor',[1 1 1]);   
    yPos2=cb2pos(2)-0.02;
% text(xPos, yPos2, ['ICnum',num2str(index)], 'color', titleColor, 'fontweight', 'bold', 'fontsize', 12 + 1, 'HorizontalAlignment', 'center', 'FontName', 'times', 'parent', axisH,'hittest','off');
  [dd, FileName, extn] = fileparts(deblank(templatelist(index,:)));
     temp_title=FileName;
% text(xPos, yPos2, ['ICnum',num2str(index)], 'color', titleColor, 'fontweight', 'bold', 'fontsize', 12 + 1, 'HorizontalAlignment', 'center', 'FontName', 'times', 'parent', axisH,'hittest','off');
text(xPos, yPos2,temp_title , 'color', titleColor, 'fontweight', 'bold', 'fontsize', 12 + 1, 'HorizontalAlignment', 'center', 'FontName', 'times', 'parent', axisH,'hittest','off');
        

set(gH,'name',fig_title);

set(handles_data.next,'enable','on');
set(handles_data.previous,'enable','on');

fprintf('New component is done!\n');
toc;
 if ishandle(h)
    delete(h);
 end
 

%% 
function handles_data=toggleImage(index,matlist,fnamelist,handles_data)
file=fnamelist(index,:);
templist=handles_data.templatelist;
tempfile=templist(index,:);
mat=matlist(index,:);
structVol=handles_data.structVol;
coords =handles_data.coords;
cmap=handles_data.cmap ;
convertToZ=1;
returnValue=1;
threshold=3;
returnInterpdata=0;
isInteractive = 1;
set_to_max_voxel = 1;
[images, real_world_coords] = ica_resizeImage(structVol, file, 'axial', [], 1);
[images2, real_world_coords] = ica_resizeImage(structVol, tempfile, 'axial', [], 1);
%structData = reshape(images(1, :, :, :), structVol.dim(1:3));
data = reshape(images(2, :, :, :), [size(images, 2), size(images, 3), size(images, 4)]);
tempdata= reshape(images2(2, :, :, :), [size(images2, 2), size(images2, 3), size(images2, 4)]);
structData = reshape(images(1, :, :, :), [size(images, 2), size(images, 3), size(images, 4)]);
clear images;

stdData = 1;
meanData = 0;
if (convertToZ)
    meanData = mean(data(data~=0));
    stdData = std(data(data~=0));
    data(data~=0) =  (data(data ~= 0) - meanData)/stdData;
    
    tempmeanData = mean(tempdata(tempdata~=0));
    tempstdData = std(tempdata(tempdata~=0));
    tempdata(tempdata~=0) =  (tempdata(tempdata ~= 0) - tempmeanData)/tempstdData;
end

data = applyDispParams(data, returnValue, threshold);
tempdata = applyDispParams(tempdata, returnValue, threshold);

good_inds = find(abs(data) > eps);
tempgood_inds = find(abs(tempdata) > eps);

minICAIM = min(data(good_inds));
maxICAIM = max(data(good_inds));

tempminICAIM = min(tempdata(tempgood_inds));
tempmaxICAIM = max(tempdata(tempgood_inds));

maxICAIM = max([maxICAIM, abs(threshold)]);
tempmaxICAIM = max([tempmaxICAIM, abs(threshold)]);

if (isempty(minICAIM))
    minICAIM = eps;
end

if (isempty(maxICAIM))
    maxICAIM = eps;
end

if (returnValue == 1)
    maxICAIM = max(abs([minICAIM, maxICAIM]));
    minICAIM = -maxICAIM;
    
    tempmaxICAIM = max(abs([tempminICAIM, tempmaxICAIM]));
    tempminICAIM = -tempmaxICAIM;
end
dataRange = [minICAIM, maxICAIM];
tempdataRange = [tempminICAIM, tempmaxICAIM];

[dd, inds] = max(abs(data(:)));
[dd2, inds2] = max(abs(tempdata(:)));

[x, y, z] = ind2sub(size(data), inds);
[x2, y2, z2] = ind2sub(size(tempdata), inds2);

maxVoxelPos = squeeze(real_world_coords(x, y, z, :))';
maxVoxelPos2 = squeeze(real_world_coords(x2, y2, z2, :))';

% if (~set_to_max_voxel)
% %     pixelPos = round(icatb_real_to_voxel(structVol, coords(1, :)));
% else
    pixelPos = [x, y, z];
    temppixelPos = [x2, y2, z2];
% end


maxICAIM = round(maxICAIM*10)/10;
minICAIM = round(minICAIM*10)/10;

tempmaxICAIM = round(tempmaxICAIM*10)/10;
tempmaxICAIM = round(tempmaxICAIM*10)/10;

minICAIM = round(minICAIM*10)/10;minICAIM = round(minICAIM*10)/10;
tempminICAIM = round(tempminICAIM*10)/10;tempminICAIM = round(tempminICAIM*10)/10;
minInterval = 0;
maxInterval = 100;

% if (isempty(cmap))
%     cmap = icatb_getColormap(1, returnValue, 1);
%     if (returnValue == 1)
%         colorLength = size(cmap, 1)/2;
%         load icatb_colors coldhot;
%         nToSkip = ceil(size(coldhot, 1)/colorLength);
%         cmap(1:colorLength, :) = coldhot(1:nToSkip:end, :);
%     end
% else
    cmap = [cmap; gray(size(cmap, 1))];
% end

CLIM = [minInterval, 2*maxInterval];

if (returnInterpdata)
    composite_data = getCompositeData(structData, data, returnValue, minInterval, maxInterval, dataRange);
    handles_data.data = composite_data;
    
     composite_data = getCompositeData(structData, tempdata, returnValue, minInterval, maxInterval, tempdataRange);
    handles_data.tempdata = composite_data;
else
    handles_data.dispPrefs = struct('returnValue', returnValue, 'stdData', stdData, 'meanData', meanData, 'imgVol', ...
        ica_returnHInfo(file), 'threshold', threshold);
    handles_data.tempdispPrefs = struct('returnValue', returnValue, 'stdData', tempstdData, 'meanData', tempmeanData, 'imgVol', ...
        ica_returnHInfo(tempfile), 'threshold', threshold);
end
handles_data.file = file;
handles_data.tempfile = tempfile;
handles_data.mat=mat;
handles_data.CLIM = CLIM;
handles_data.range = dataRange;
handles_data.temprange = tempdataRange;
handles_data.minInterval = minInterval;
handles_data.maxInterval = maxInterval;
handles_data.pixelPos = pixelPos;
handles_data.temppixelPos = temppixelPos;
handles_data.coords = coords;
handles_data.origin = [0, 0, 0];
handles_data.voxelOrigin = ica_real_to_voxel(structVol(1), handles_data.origin);
handles_data.VOX = abs([structVol(1).mat(1, 1), structVol(1).mat(2, 2), structVol(1).mat(3, 3)]);
handles_data.structVol = structVol;
handles_data.minICAIM = minICAIM;
handles_data.maxICAIM = maxICAIM;

handles_data.tempminICAIM = tempminICAIM;
handles_data.tempmaxICAIM = tempmaxICAIM;
% handles_data.labels = labels;
handles_data.maxVoxelPos = maxVoxelPos;
handles_data.maxVoxelPos2 = maxVoxelPos2;
handles_data.isInteractive = isInteractive;
handles_data.cmap = cmap;
 
if (returnInterpdata)
    handles_data.maxVoxelPos = handles_data.pixelPos;
    varargout{1} = handles_data;
    return;
end

if exist('tc', 'var')
    handles_data.numRowsToPlot = (size(coords, 1) + 1);
else
    handles_data.numRowsToPlot = (size(coords, 1));
end

  


function subH = plotImage(subH, data, CLIM)
%% Function to plot the image at the specified position
%

imageAxisPos = get(subH, 'position');
image(rot90(data), 'parent', subH, 'CDataMapping', 'scaled');
set(subH, 'units', 'normalized');
oldWidth = imageAxisPos(3);
oldHeight = imageAxisPos(4);
yAxisRatio = imageAxisPos(4)/imageAxisPos(3);
xAxisRatio = imageAxisPos(3)/imageAxisPos(4);
if(yAxisRatio>1)
    yAxisRatio = 1;
else
    xAxisRatio = 1;
end
newWidth = imageAxisPos(3)*yAxisRatio;
newHeight = imageAxisPos(4)*xAxisRatio;

if (newHeight < oldHeight)
    imageAxisPos(2) = imageAxisPos(2) + 0.5*(oldHeight - newHeight);
end

imageAxisPos = [imageAxisPos(1), imageAxisPos(2), newWidth, newHeight];
set(subH, 'position', imageAxisPos);
%setImagePos(subH, imagePos);
set(subH, 'clim', CLIM); % set the axis positions to the specified
axis(subH, 'image');
set(subH, 'XTick', []);
set(subH, 'XTickLabel', []);
set(subH, 'YTick', []);
set(subH, 'YTickLabel', []);


function [sliceXY, sliceXZ, sliceYZ] = returnSlices(handles_data, voxelcoords)
%% Slices (XY, XZ, YZ)


%% XY
[sliceXY, structData] = getData(handles_data.structVol, handles_data.dispPrefs.imgVol, 'axial', voxelcoords(end));
sliceXY = applyDispParams((sliceXY - handles_data.dispPrefs.meanData) / handles_data.dispPrefs.stdData, ...
    handles_data.dispPrefs.returnValue, handles_data.dispPrefs.threshold);
sliceXY = getCompositeData(structData, sliceXY, handles_data.dispPrefs.returnValue, handles_data.minInterval, handles_data.maxInterval, handles_data.range);


%% XZ
[sliceXZ, structData] = getData(handles_data.structVol, handles_data.dispPrefs.imgVol, 'coronal', voxelcoords(2));
sliceXZ = applyDispParams((sliceXZ - handles_data.dispPrefs.meanData) / handles_data.dispPrefs.stdData, ...
    handles_data.dispPrefs.returnValue, handles_data.dispPrefs.threshold);
sliceXZ = getCompositeData(structData, sliceXZ, handles_data.dispPrefs.returnValue, handles_data.minInterval, handles_data.maxInterval, handles_data.range);

%% YZ
[sliceYZ, structData] = getData(handles_data.structVol, handles_data.dispPrefs.imgVol, 'sagittal', voxelcoords(1));
sliceYZ = applyDispParams((sliceYZ - handles_data.dispPrefs.meanData) / handles_data.dispPrefs.stdData, ...
    handles_data.dispPrefs.returnValue, handles_data.dispPrefs.threshold);
sliceYZ = getCompositeData(structData, sliceYZ, handles_data.dispPrefs.returnValue, handles_data.minInterval, handles_data.maxInterval, handles_data.range);


function [sliceXY, sliceXZ, sliceYZ] = tempreturnSlices(handles_data, voxelcoords)
%% Slices (XY, XZ, YZ)


%% XY
[sliceXY, structData] = getData(handles_data.structVol, handles_data.tempdispPrefs.imgVol, 'axial', voxelcoords(end));
sliceXY = applyDispParams((sliceXY - handles_data.tempdispPrefs.meanData) / handles_data.tempdispPrefs.stdData, ...
    handles_data.tempdispPrefs.returnValue, handles_data.tempdispPrefs.threshold);
sliceXY = getCompositeData(structData, sliceXY, handles_data.tempdispPrefs.returnValue, handles_data.minInterval, handles_data.maxInterval, handles_data.temprange);


%% XZ
[sliceXZ, structData] = getData(handles_data.structVol, handles_data.tempdispPrefs.imgVol, 'coronal', voxelcoords(2));
sliceXZ = applyDispParams((sliceXZ - handles_data.tempdispPrefs.meanData) / handles_data.tempdispPrefs.stdData, ...
    handles_data.tempdispPrefs.returnValue, handles_data.tempdispPrefs.threshold);
sliceXZ = getCompositeData(structData, sliceXZ, handles_data.tempdispPrefs.returnValue, handles_data.minInterval, handles_data.maxInterval, handles_data.temprange);

%% YZ
[sliceYZ, structData] = getData(handles_data.structVol, handles_data.tempdispPrefs.imgVol, 'sagittal', voxelcoords(1));
sliceYZ = applyDispParams((sliceYZ - handles_data.tempdispPrefs.meanData) / handles_data.tempdispPrefs.stdData, ...
    handles_data.tempdispPrefs.returnValue, handles_data.tempdispPrefs.threshold);
sliceYZ = getCompositeData(structData, sliceYZ, handles_data.tempdispPrefs.returnValue, handles_data.minInterval, handles_data.maxInterval, handles_data.temprange);






function scaledData = scaleIm(tmin, tmax, imageData, returnValue, data_range)
%% Scale images
%

if (~exist('returnValue', 'var'))
    returnValue = 2;
end

if (~exist('data_range', 'var'))
    minVal = min(imageData);
    maxVal = max(imageData);
else
    minVal = min(data_range);
    maxVal = max(data_range);
end

if (returnValue == 1)
    maxVal = max(abs([minVal, maxVal]));
    minVal = -maxVal;
end

rangeVal = (maxVal-minVal) + eps;
trange = tmax-tmin;
if (rangeVal == 0)
    rangeVal = eps;
end
scaledData = (((imageData-minVal)./rangeVal)./(1/trange))+tmin;

function updateSlices(handles_data)
%% Update slices and labels

%realCoords = (icatb_voxel_to_real(handles_data.structVol, handles_data.coords(1, :)));
realCoords = handles_data.coords(1, :);
[sliceXY, sliceXZ, sliceYZ] = returnSlices(handles_data, realCoords);
[sliceXY2, sliceXZ2, sliceYZ2] = tempreturnSlices(handles_data, realCoords);
%% X
set(findobj(handles_data.allAxes(1), 'Type', 'Image'), 'CData', rot90(sliceYZ));
set(get(handles_data.allAxes(1), 'XLabel'), 'string', ['X = ', num2str(realCoords(1)), ' mm']);

set(findobj(handles_data.allAxes2(1), 'Type', 'Image'), 'CData', rot90(sliceYZ2));
set(get(handles_data.allAxes2(1), 'XLabel'), 'string', ['X = ', num2str(realCoords(1)), ' mm']);

%% Y
set(findobj(handles_data.allAxes(2), 'Type', 'Image'), 'CData', rot90(sliceXZ));
set(get(handles_data.allAxes(2), 'XLabel'), 'string', ['Y = ', num2str(realCoords(2)), ' mm']);

set(findobj(handles_data.allAxes2(2), 'Type', 'Image'), 'CData', rot90(sliceXZ2));
set(get(handles_data.allAxes2(2), 'XLabel'), 'string', ['Y = ', num2str(realCoords(2)), ' mm']);
%% Z
set(findobj(handles_data.allAxes(3), 'Type', 'Image'), 'CData', rot90(sliceXY));
set(get(handles_data.allAxes(3), 'XLabel'), 'string', ['Z = ', num2str(realCoords(3)), ' mm']);

set(findobj(handles_data.allAxes2(3), 'Type', 'Image'), 'CData', rot90(sliceXY2));
set(get(handles_data.allAxes2(3), 'XLabel'), 'string', ['Z = ', num2str(realCoords(3)), ' mm']);

set(handles_data.allAxes, 'CLIM', handles_data.CLIM);
set(handles_data.allAxes2, 'CLIM', handles_data.tempCLIM);

set(handles_data.ch, 'xLim', [handles_data.minInterval, handles_data.maxInterval]);
set(handles_data.ch2, 'xLim', [handles_data.minInterval, handles_data.maxInterval]);

xTicks = get(handles_data.ch, 'xTick');
set(handles_data.ch, 'xTick', [xTicks(1), xTicks(end)]);
set(handles_data.ch, 'xTicklabel', cellstr(num2str([handles_data.minICAIM;handles_data.maxICAIM])));

xTicks = get(handles_data.ch2, 'xTick');
set(handles_data.ch2, 'xTick', [xTicks(1), xTicks(end)]);
set(handles_data.ch2, 'xTicklabel', cellstr(num2str([handles_data.tempminICAIM;handles_data.tempmaxICAIM])));

function setVoxelPos(hObject, event_data, handles)
%% Set Voxel Position

handles_data = get(handles, 'userdata');

% open input dialog box
prompt = {'Enter voxel position in real world coordinates (mm)'};
dlg_title = 'Set voxel position';
num_lines = 1;
def = {num2str(handles_data.coords(1, :))};
%def = {num2str((icatb_voxel_to_real(handles_data.structVol, handles_data.coords)))};

% get voxel coords
voxelPos = ica_inputdlg2(prompt, dlg_title, num_lines, def);
drawnow;

if (~isempty(voxelPos))
    voxelPos = str2num(voxelPos{1});
    if length(voxelPos) ~= 3
        error('Please enter the three coords correctly');
    end
    %handles_data.coords = round(icatb_real_to_voxel(handles_data.structVol, voxelPos));
    handles_data.coords = voxelPos;
    %voxelOrigin = icatb_real_to_voxel(handles_data.structVol(1), handles_data.origin);
    voxelOrigin = handles_data.voxelOrigin;
    handles_data.pixelPos = round(voxelOrigin + (voxelPos./handles_data.VOX));
    set(handles, 'userdata', handles_data);
    updateSlices(handles_data);
end

function setMaxVoxel(hObject, event_data, handles)
%% Set Max voxel

handles_data = get(handles, 'userdata');
handles_data.coords = handles_data.maxVoxelPos;
handles_data.pixelPos = round(handles_data.voxelOrigin + (handles_data.coords./handles_data.VOX));
%handles_data.centre = handles_data.maxVoxelPos;
set(handles, 'userdata', handles_data);
updateSlices(handles_data);

function [data, structData] = getData(structVol, imgVol, anatomicalView, slices)
%% Get data
%

parameters =  ica_get_slice_def(structVol, 'axial');
transform = parameters.transform;
slicedef = parameters.slicedef;
%
X = 1;Y = 2; Z = 3;
dims = slicedef;
xmm = dims(X,1):dims(X,2):dims(X,3);
ymm = dims(Y,1):dims(Y,2):dims(Y,3);
zmm = parameters.slices;
if (strcmpi(anatomicalView, 'axial'))
    zmm = slices;
end
if (strcmpi(anatomicalView, 'coronal'))
    ymm = slices;
end
if (strcmpi(anatomicalView, 'sagittal'))
    xmm = slices;
end

[y, x] = meshgrid(ymm, xmm');
vdims = [length(xmm), length(ymm), length(zmm)];
nslices = vdims(Z);
nvox = prod(vdims(1:2));

structData = zeros(vdims);
data = zeros(vdims);
for ii = 1:nslices
    ixyzmm = [x(:)'; y(:)'; ones(1,nvox)*zmm(ii); ones(1, nvox)];
    vixyz = (transform*imgVol(1).mat) \ ixyzmm;
    i1 = spm_sample_vol(imgVol(1), vixyz(X, :), vixyz(Y, :), vixyz(Z, :), [1, nan]);
    data(:, :, ii) = reshape(i1, vdims(1:2));
    vixyz = (transform*structVol(1).mat) \ ixyzmm;
    i1 = spm_sample_vol(structVol(1), vixyz(X, :), vixyz(Y, :), vixyz(Z, :), [1, nan]);
    structData(:, :, ii) = reshape(i1, vdims(1:2));
end

data(isfinite(data) == 0) = 0;
structData(isfinite(structData) == 0) = 0;

data = squeeze(data);
structData = squeeze(structData);

function data = applyDispParams(data, returnValue, threshold)
%% Apply display parameters

threshold = abs(threshold);

if (returnValue == 2)
    % Positive
    data(data < 0) = 0;
elseif (returnValue == 3)
    % Absolute value
    data = abs(data);
elseif (returnValue == 4)
    % Negative value
    data(data > 0) = 0;
end

if (length(threshold) > 1)
    
    if ((returnValue == 2) || (returnValue == 3))
        % Positive or absolute
        data(data < min(threshold)) = 0;
        data(data > max(threshold)) = max(threshold);
    elseif (returnValue == 4)
        % Negative
        data(abs(data) < min(threshold)) = 0;
        data(abs(data) > max(threshold)) = -max(threshold);
    else
        % Positive and Negative
        neg_threshold = -threshold;
        
        pos_inds = (data > 0);
        neg_inds = (data < 0);
        
        % Handle positive range
        tmp1 = data(pos_inds);
        tmp1(tmp1 < min(threshold)) = 0;
        tmp1(tmp1 > max(threshold)) = max(threshold);
        
        % handle negative range
        tmp2 = data(neg_inds);
        tmp2(tmp2 > max(neg_threshold)) = 0;
        tmp2(tmp2 < min(neg_threshold)) = min(neg_threshold);
        
        data(pos_inds) = tmp1;
        data(neg_inds) = tmp2;
    end
 
else
    data(abs(data) < threshold) = 0;
end

function composite_data = getCompositeData(structData, data, returnValue, minInterval, maxInterval, data_range)
%% Get composite data

good_inds = find(abs(data) > eps);

unitColor = ica_range(data(:))/64;

if (exist('data_range', 'var'))
    data(data == data_range(2)) = data(data == data_range(2)) - unitColor;
end

% Overlay components
composite_data = scaleIm(maxInterval + 1, 2*maxInterval, structData(:));
if (~isempty(good_inds))
    if (~exist('data_range', 'var'))
        composite_data(good_inds) = scaleIm(minInterval, maxInterval, data(good_inds), returnValue);
    else
        composite_data(good_inds) = scaleIm(minInterval, maxInterval, data(good_inds), returnValue, data_range);
    end
end
clear data;

composite_data = reshape(composite_data, size(structData));

function quad1Callback(hObject, event_data, handles)
%% Quad1

handles_data = get(handles, 'userdata');
pixelPos = handles_data.pixelPos;
childH = get(hObject, 'children');
data = get(childH, 'CData')';
imDIM = size(data);
points = get(hObject, 'currentPoint');
x = points(1, 1);
y = points(1, 2);
newY = ceil(x);
newZ = ceil(imDIM(end) - y);
if ((newY < 1) || (newY > imDIM(1)))
    return;
end
if ((newZ < 1) || (newZ > imDIM(end)))
    return;
end
pixelPos(2:3) = [newY, newZ];
handles_data.coords = (pixelPos - handles_data.voxelOrigin).*handles_data.VOX;
handles_data.pixelPos = pixelPos;
set(handles, 'userdata', handles_data);
updateSlices(handles_data);

function quad2Callback(hObject, event_data, handles)
%% Quad2

handles_data = get(handles, 'userdata');
pixelPos = handles_data.pixelPos;
childH = get(hObject, 'children');
data = get(childH, 'CData')';
imDIM = size(data);
points = get(hObject, 'currentPoint');
x = points(1, 1);
y = points(1, 2);
newX = ceil(x);
newZ = ceil(imDIM(end)-y);

if ((newX < 1) || (newX > imDIM(1)))
    return;
end

if ((newZ < 1) || (newZ > imDIM(end)))
    return;
end

pixelPos([1, 3]) = [newX, newZ];
handles_data.coords = (pixelPos - handles_data.voxelOrigin).*handles_data.VOX;
handles_data.pixelPos = pixelPos;
set(handles, 'userdata', handles_data);
updateSlices(handles_data);

function quad3Callback(hObject, event_data, handles)
%% Quad3

handles_data = get(handles, 'userdata');
pixelPos = handles_data.pixelPos;
childH = get(hObject, 'children');
data = get(childH, 'CData')';
imDIM = size(data);
points = get(hObject, 'currentPoint');
x = points(1, 1);
y = points(1, 2);
newX = ceil(x);
newY = ceil(imDIM(2)-y);

if ((newX < 1) || (newX > imDIM(1)))
    return;
end

if ((newY < 1) || (newY > imDIM(end)))
    return;
end

pixelPos(1:2) = [newX, newY];
handles_data.coords = (pixelPos - handles_data.voxelOrigin).*handles_data.VOX;
handles_data.pixelPos = pixelPos;
set(handles, 'userdata', handles_data);
updateSlices(handles_data);

%% 
 function region= calcuRegion(ic,aalData,template,tempNum)
flag=0;
[dd, FileName, extn] = fileparts(deblank(ic));
rfile=strcat(dd,filesep,'r',FileName,'.nii');

%     target_image=ic;
%     MASK_image=template;
%     P=char(MASK_image,target_image);
% 
%     spm_reslice(P);
    
    InputFile=ic; 
    OutputFile=rfile;
    hld=0;
    TargetSpace=template;
    GIGICA_resliceImage(InputFile,OutputFile,hld, TargetSpace);
    



v1=spm_vol(rfile);
 
icData=spm_read_vols(v1);



[M,N,L]=size(aalData);
regionID=unique(aalData);
regionID(regionID==0)=[];

regionNum=length(regionID);

for times=1:regionNum
    ID=regionID(times);
    aalData2=aalData;
    volSize=0;
%     regionSize=0;
    netSize=0;
    for i=1:M
        for j=1:N
            for k=1:L
                if aalData(i,j,k)~=ID
                    aalData2(i,j,k)=0;
                end
                if icData(i,j,k)>=3
                    netSize=netSize+1;
                end
            end
        end
    end
    for i=1:M
        for j=1:N
            for k=1:L
                if aalData2(i,j,k)==ID && icData(i,j,k)>=3
                    volSize=volSize+1;
                end
            end
        end
    end
    rate=volSize/netSize;
    rate=round(rate*1000)/1000;
    volRateMatrix(times,1)=rate;
%     volRateMatrix(times,2)=ID;
%     if times~=ID
%         volRateMatrix(times,1)=0;
%         volRateMatrix(times,2)=-1;
%     end
end
% fig_dir=fileparts(template);
[fig_dir, aalname, extn] = fileparts(template);
[sortResult,index]=sort(volRateMatrix,'descend');
switch aalname
    case 'aal'
        aalname='AAL';
        templateName=fullfile(fig_dir,'aalROI.mat');%ROI
    case 'AAL3v1'
        aalname='AAL3';
        templateName=fullfile(fig_dir,'ROI_MNI_V7_List.mat');%ROI
    case 'BNA_MPM_thr25_1.25mm'
        aalname='BNA';
        templateName=fullfile(fig_dir,'BNAtemplate.mat');%ROI
end
load(templateName);
switch tempNum
    case 1
        region=strcat(aalname,':',ROI(index(1)).Nom_L,'(',num2str(sortResult(1)),')');
    case 2
        region=strcat(aalname,':',ROI(index(1)).Nom_L,'(',num2str(sortResult(1)),')',',',ROI(index(2)).Nom_L,'(',num2str(sortResult(2)),')');
    case 3
        region=strcat(aalname,':',ROI(index(1)).Nom_L,'(',num2str(sortResult(1)),')',',',ROI(index(2)).Nom_L,'(',num2str(sortResult(2)),')',',',ROI(index(3)).Nom_L,'(',num2str(sortResult(3)),')');
end
