%  Create Brain 3-View (Front, Top, Side) of the brain data
%  that specified by avw structure, and plot it on the area
%  that specified by plot structure.
%
%  Usage: rri_view_avw(avw, [plot]);
%
%  where:
%	avw:		brain data in AVW format
%	plot.figure:	main figure
%	plot.area:	3 view ploting area
%
%  e.g.:
%	avw = rri_load_avw('T1');		% T1.img/hdr
%	rri_view_avw(avw);
%
%	or
%
%	plot.figure = figure('unit','normal','position',[0.18 0.08 0.64 0.8]);
%	plot.area = [0.05 0.05 0.9 0.9];
%	rri_view_avw(avw, plot);
%
%
%  Part (or all) of this file is copied and modified under GNU license
%  from MRI_TOOLBOX developed by CNSP in Flinders University, Australia
%
function GUI = rri_view_avw(avw, varargin)

   if nargin < 1
      msg = sprintf('Please check inputs using ''help rri_avw3vie''');
      error(msg);

      return;
   end;

   if nargin > 1
      gui3view = varargin{1};
   else
      gui3view.figure = figure('unit','normal','position',[0.18 0.08 0.64 0.8]);
      gui3view.area = [0.05 0.05 0.9 0.9];
   end

   if nargin > 2
      command = lower(varargin{2});
   else
      command = 'init';
   end

   if nargin > 3
      isrhos = varargin{3};
   else
      isrhos = 0;
   end

   if nargin > 4
      impos_init = varargin{4};
   else
      impos_init = [];
   end

   if nargin > 5
      butt_down_cmd = varargin{5};
   else
      butt_down_cmd = '';
   end

   if isempty(gui3view)
      fig = gcbf;
   else
      fig = gui3view.figure;
   end

   switch command

   case {'init'}

      if ~exist('avw','var') | ~exist('gui3view','var')
         msg = sprintf('Please input GUI handles and Brain data');
         error(msg);
      end

      if ~isstruct(avw) | ~isstruct(gui3view)
         msg = sprintf('gui3view or avw is inputed wrong');
         error(msg);
      end

      GUI = init(avw, gui3view, isrhos, impos_init, butt_down_cmd);

   case {'update_img'}

      if ~exist('avw','var') | ~exist('gui3view','var')
         msg = sprintf('Please input GUI handles and Brain data');
         error(msg);
      end

      %  avw is not avw, is img
      %
      update_img(avw, gui3view);

   case {'update_avw'}

      if ~exist('avw','var') | ~exist('gui3view','var')
         msg = sprintf('Please input GUI handles and Brain data');
         error(msg);
      end

      if ~isstruct(gui3view) | ~isstruct(avw)
         msg = sprintf('gui3view or avw is inputed wrong');
         error(msg);
      end

      update_avw(avw, gui3view, isrhos, impos_init, butt_down_cmd);

   case {'axial_image','coronal_image','sagittal_image'}    

      switch command
         case 'axial_image',    view = 'axi'; axi = 0; cor = 1; sag = 1;
         case 'coronal_image',  view = 'cor'; axi = 1; cor = 0; sag = 1;
         case 'sagittal_image', view = 'sag'; axi = 1; cor = 1; sag = 0;
      end

      AVWVIEW = getappdata(fig,'AVWVIEW');
      AVWVIEW = get_slice_position(AVWVIEW,view);

      if isfield(AVWVIEW, 'disp')
         img = AVWVIEW.disp;    
      else
         img = AVWVIEW.avw.img;
      end

      if axi,
         if isfield(AVWVIEW.handles,'axial_image'),
            Saxi = squeeze(img(:,:,AVWVIEW.slices.axi));
            set(AVWVIEW.handles.axial_image,'CData',Saxi'); drawnow;
         end

         if isfield(AVWVIEW.handles,'axial_slider'),
            set(AVWVIEW.handles.axial_slider,'Value',AVWVIEW.slices.axi);
         end;
       end
    
       if cor,
         if isfield(AVWVIEW.handles,'coronal_image'),
            Scor = squeeze(img(:,AVWVIEW.slices.cor,:));
            set(AVWVIEW.handles.coronal_image,'CData',Scor'); drawnow;
         end

         if isfield(AVWVIEW.handles,'coronal_slider'),
            slider_val = AVWVIEW.dims(2) - AVWVIEW.slices.cor + 1;
            set(AVWVIEW.handles.coronal_slider,'Value',slider_val);
         end;
      end;
    
      if sag,
         if isfield(AVWVIEW.handles,'sagittal_image'),
            Ssag = squeeze(img(AVWVIEW.slices.sag,:,:));
            set(AVWVIEW.handles.sagittal_image,'CData',Ssag'); drawnow;
         end

         if isfield(AVWVIEW.handles,'sagittal_slider'),
            set(AVWVIEW.handles.sagittal_slider,'Value',AVWVIEW.slices.sag);
         end;

         if AVWVIEW.isrhos
            AVWVIEW.slices.sag = AVWVIEW.dims(1) - AVWVIEW.slices.sag + 1;
         end
      end;

      update_AVWVIEW(AVWVIEW);

      if ~isempty(AVWVIEW.butt_down_cmd)
         eval(AVWVIEW.butt_down_cmd);
      end
    
   case {'axial_slider','coronal_slider','sagittal_slider'},
    
      switch command
         case 'axial_slider',    view = 'axi'; axi = 1; cor = 0; sag = 0;
         case 'coronal_slider',  view = 'cor'; axi = 0; cor = 1; sag = 0;
         case 'sagittal_slider', view = 'sag'; axi = 0; cor = 0; sag = 1;
      end

      AVWVIEW = getappdata(fig,'AVWVIEW');
      AVWVIEW = get_slider_position(AVWVIEW);

      if isfield(AVWVIEW, 'disp')
         img = AVWVIEW.disp;    
      else
         img = AVWVIEW.avw.img;
      end

      if axi,
         set(AVWVIEW.handles.axial_slider,'Value',AVWVIEW.slices.axi);
         Saxi = squeeze(img(:,:,AVWVIEW.slices.axi));
         set(AVWVIEW.handles.axial_image,'CData',Saxi'); drawnow;
      end

      if cor,
         slider_val = AVWVIEW.dims(2) - AVWVIEW.slices.cor + 1;
         set(AVWVIEW.handles.coronal_slider,'Value',slider_val);
         Scor = squeeze(img(:,AVWVIEW.slices.cor,:));
         set(AVWVIEW.handles.coronal_image,'CData',Scor'); drawnow;
      end    

      if sag,
         if AVWVIEW.isrhos
            Ssag = squeeze(img(AVWVIEW.dims(1)-AVWVIEW.slices.sag+1,:,:));
            set(AVWVIEW.handles.sagittal_image,'CData',Ssag'); drawnow;

            set(AVWVIEW.handles.sagittal_slider,'value', ...
		AVWVIEW.dims(1) - AVWVIEW.slices.sag + 1);
         else
            Ssag = squeeze(img(AVWVIEW.slices.sag,:,:));
            set(AVWVIEW.handles.sagittal_image,'CData',Ssag'); drawnow;

            set(AVWVIEW.handles.sagittal_slider,'Value',AVWVIEW.slices.sag);
         end
      end

      update_AVWVIEW(AVWVIEW);

      if ~isempty(AVWVIEW.butt_down_cmd)
         eval(AVWVIEW.butt_down_cmd);
      end

   case {'impos_edit'}

      AVWVIEW = getappdata(fig,'AVWVIEW');
      impos = str2num(get(AVWVIEW.handles.impos,'string'));

      if isfield(AVWVIEW, 'disp')
         img = AVWVIEW.disp;    
      else
         img = AVWVIEW.avw.img;
      end

      if isempty(impos) | ~all(size(impos) ==  [1 3])
         msg = 'Please use 3 numbers to represent X,Y and Z';
         msgbox(msg,'Error');
         return;
      end

      if AVWVIEW.isrhos
         impos = impos([2 1 3]);
      end

      slices.sag = round(impos(1));
      slices.cor = round(impos(2));
      slices.axi = round(impos(3));

      AVWVIEW = convert2voxel(AVWVIEW,slices);
      AVWVIEW = check_slices(AVWVIEW);

      if AVWVIEW.isrhos
         impos(1) = AVWVIEW.dims(1) - AVWVIEW.slices.sag + 1;
      else
         impos(1) = AVWVIEW.slices.sag;
      end
      impos(2) = AVWVIEW.dims(2) - AVWVIEW.slices.cor + 1;
      impos(3) = AVWVIEW.slices.axi;

      set(AVWVIEW.handles.sagittal_slider,'Value',impos(1));
      set(AVWVIEW.handles.coronal_slider,'Value',impos(2));
      set(AVWVIEW.handles.axial_slider,'Value',impos(3));

      AVWVIEW = get_slider_position(AVWVIEW);
      update_AVWVIEW(AVWVIEW);

      set(AVWVIEW.handles.axial_slider,'Value',AVWVIEW.slices.axi);
      Saxi = squeeze(img(:,:,AVWVIEW.slices.axi));
      set(AVWVIEW.handles.axial_image,'CData',Saxi'); drawnow;

      slider_val = AVWVIEW.dims(2) - AVWVIEW.slices.cor + 1;
      set(AVWVIEW.handles.coronal_slider,'Value',slider_val);
      Scor = squeeze(img(:,AVWVIEW.slices.cor,:));
      set(AVWVIEW.handles.coronal_image,'CData',Scor'); drawnow;

      if AVWVIEW.isrhos
         Ssag = squeeze(img(AVWVIEW.dims(1)-AVWVIEW.slices.sag+1,:,:));
         set(AVWVIEW.handles.sagittal_image,'CData',Ssag'); drawnow;

         set(AVWVIEW.handles.sagittal_slider,'value', ...
		AVWVIEW.dims(1) - AVWVIEW.slices.sag + 1);
      else
         Ssag = squeeze(img(AVWVIEW.slices.sag,:,:));
         set(AVWVIEW.handles.sagittal_image,'CData',Ssag'); drawnow;

         set(AVWVIEW.handles.sagittal_slider,'Value',AVWVIEW.slices.sag);
      end

      if ~isempty(AVWVIEW.butt_down_cmd)
         eval(AVWVIEW.butt_down_cmd);
      end

   case 'coordinates',

      AVWVIEW = getappdata(fig,'AVWVIEW');
      set_image_value(AVWVIEW);

   case 'crosshair',

      AVWVIEW = getappdata(fig,'AVWVIEW');

      if get(AVWVIEW.handles.xhair,'value') == 2		% off
         set(AVWVIEW.axi_xhair.lx,'visible','off');
         set(AVWVIEW.axi_xhair.ly,'visible','off');
         set(AVWVIEW.cor_xhair.lx,'visible','off');
         set(AVWVIEW.cor_xhair.ly,'visible','off');
         set(AVWVIEW.sag_xhair.lx,'visible','off');
         set(AVWVIEW.sag_xhair.ly,'visible','off');
      else
         set(AVWVIEW.axi_xhair.lx,'visible','on');
         set(AVWVIEW.axi_xhair.ly,'visible','on');
         set(AVWVIEW.cor_xhair.lx,'visible','on');
         set(AVWVIEW.cor_xhair.ly,'visible','on');
         set(AVWVIEW.sag_xhair.lx,'visible','on');
         set(AVWVIEW.sag_xhair.ly,'visible','on');

         set(AVWVIEW.handles.axial_axes,'selected','on');
         set(AVWVIEW.handles.axial_axes,'selected','off');
         set(AVWVIEW.handles.coronal_axes,'selected','on');
         set(AVWVIEW.handles.coronal_axes,'selected','off');
         set(AVWVIEW.handles.sagittal_axes,'selected','on');
         set(AVWVIEW.handles.sagittal_axes,'selected','off');
      end

   case 'xhair_color',

      AVWVIEW = getappdata(fig,'AVWVIEW');
      old_color = get(gcbo,'user');
      new_color = uisetcolor(old_color);
      set(gcbo,'user',new_color);

      set(AVWVIEW.axi_xhair.lx,'color',new_color);
      set(AVWVIEW.axi_xhair.ly,'color',new_color);
      set(AVWVIEW.cor_xhair.lx,'color',new_color);
      set(AVWVIEW.cor_xhair.ly,'color',new_color);
      set(AVWVIEW.sag_xhair.lx,'color',new_color);
      set(AVWVIEW.sag_xhair.ly,'color',new_color);

   case {'neg_color','color','brightness','contrast'}

      change_color_map(fig);

   case {'brightness_def'}

      AVWVIEW = getappdata(fig,'AVWVIEW');
      set(AVWVIEW.handles.brightness,'value',0);
      change_color_map(fig);

   case {'contrast_def'}

      AVWVIEW = getappdata(fig,'AVWVIEW');
      set(AVWVIEW.handles.contrast,'value',1);
      change_color_map(fig);

   case {'change_color_map'}

      change_color_map(fig);

   case 'hist_plot'

      hist_plot(fig);

   case 'hist_eq'

      hist_eq(fig);

   end

   return;						% rri_view_avw


%----------------------------------------------------------------
function GUI = init(avw, gui3view, isrhos, impos_init, butt_down_cmd)

   GUI = gui3view.figure;
   area = gui3view.area;
   AVWVIEW = getappdata(GUI, 'AVWVIEW');

   switch double(avw.hdr.dime.bitpix)
   case 1
      avw.img = uint8(avw.img);			% binary
   case 8
      avw.img = uint8(avw.img);			% unsigned char
   case 16
      avw.img = int16(avw.img);			% signed short
   case 32
      if isequal(avw.hdr.dime.datatype, 8), 
         avw.img = int32(avw.img);		% signed integer
      else
         avw.img = single(avw.img);		% float
      end
   case 64
      avw.img = double(avw.img);		% double
   otherwise
      msgbox('Incorrect image header');
      return;
   end

   %  init color (gray) scaling
   %
   clim = [min(avw.img(:)) max(avw.img(:))];

   xdim = size(avw.img, 1);
   ydim = size(avw.img, 2);
   zdim = size(avw.img, 3);

   dims = [xdim ydim zdim];
   voxel_size = double(avw.hdr.dime.pixdim(2:4));	% vol in mm
   origin = double(avw.hdr.hist.originator(1:3));

   if isempty(origin) | all(origin == 0)		% according to SPM
      origin = (dims+1)/2;   
   end;

   if any(origin > dims)				% simulate fMRI
      origin(find(origin > dims)) = dims(find(origin > dims));
   end

   origin = floor(origin);

   %  update AVWVIEW
   %
   if ~isfield(AVWVIEW, 'dims') | ...
      ~isfield(AVWVIEW, 'voxel_size') | ...
      ~isfield(AVWVIEW, 'origin') | ...
      ~isequal(AVWVIEW.dims, dims) | ...
      ~isequal(AVWVIEW.voxel_size, voxel_size) | ...
      ~isequal(AVWVIEW.origin, origin)

      AVWVIEW.dims = dims;
      AVWVIEW.voxel_size = voxel_size;
      AVWVIEW.origin = origin;

      AVWVIEW.slices.sag = 1;
      AVWVIEW.slices.cor = 1;
      AVWVIEW.slices.axi = 1;
      if xdim > 1, AVWVIEW.slices.sag = origin(1); end
      if ydim > 1, AVWVIEW.slices.cor = origin(2); end
      if zdim > 1, AVWVIEW.slices.axi = origin(3); end

      if ~isempty(impos_init)
         if xdim > 1, AVWVIEW.slices.sag = impos_init(1); end
         if ydim > 1, AVWVIEW.slices.cor = impos_init(2); end
         if zdim > 1, AVWVIEW.slices.axi = impos_init(3); end
      end

      %  if size does not match, delete xhair if exist
      %
      if isfield(AVWVIEW,'axi_xhair') & ~isempty(AVWVIEW.axi_xhair) ...
         & ishandle(AVWVIEW.axi_xhair.lx)

         delete(AVWVIEW.axi_xhair.lx);
         delete(AVWVIEW.axi_xhair.ly);
         delete(AVWVIEW.cor_xhair.lx);
         delete(AVWVIEW.cor_xhair.ly);
         delete(AVWVIEW.sag_xhair.lx);
         delete(AVWVIEW.sag_xhair.ly);

         AVWVIEW.axi_xhair = [];
         AVWVIEW.cor_xhair = [];
         AVWVIEW.sag_xhair = [];
      end
   end

   AVWVIEW.area = area;
   AVWVIEW.gui = GUI;
   AVWVIEW.avw = avw;					% image data

   Font.FontUnits  = 'point';
   Font.FontSize   = 12;

   %  create axes for top/front/side view
   %
   vol_size = voxel_size .* dims;
   [top_ax, front_ax, side_ax] = create_ax(GUI, area, vol_size);

   top_pos = get(top_ax,'position');
   front_pos = get(front_ax,'position');
   side_pos = get(side_ax,'position');

   %  Sagittal Slider
   %
   x = top_pos(1);
   y = top_pos(2) + top_pos(4);
   w = top_pos(3);
   h = front_pos(2) - y;

   pos = [x y w h];

   if xdim > 1,
      slider_step(1) = 1/(xdim);
      slider_step(2) = 1.00001/(xdim);

      handles.sagittal_slider = uicontrol('Parent',GUI, ...
                'Style','slider','Units','Normalized', Font, ...
                'Position',pos, 'HorizontalAlignment','center',...
                'BackgroundColor',[0.5 0.5 0.5],'ForegroundColor',[0 0 0],...
                'BusyAction','queue',...
                'TooltipString','Sagittal slice navigation',...
                'Min',1,'Max',xdim,'SliderStep',slider_step, ...
                'Value',AVWVIEW.slices.sag,...
                'Callback','rri_view_avw([],[],''sagittal_slider'');');

      set(handles.sagittal_slider,'position',pos);	% linux66

      if isrhos
         set(handles.sagittal_slider,'value',xdim-AVWVIEW.slices.sag+1);
      end
   end

   %  Coronal Slider
   %
   x = side_pos(1);
   y = top_pos(2) + top_pos(4);
   w = side_pos(3);
   h = front_pos(2) - y;

   pos = [x y w h];

   if ydim > 1,
      slider_step(1) = 1/(ydim);
      slider_step(2) = 1.00001/(ydim);

      slider_val = AVWVIEW.dims(2) - AVWVIEW.slices.cor + 1;

      handles.coronal_slider = uicontrol('Parent',GUI, ...
                'Style','slider','Units','Normalized', Font, ...
                'Position',pos, 'HorizontalAlignment','center',...
                'BackgroundColor',[0.5 0.5 0.5],'ForegroundColor',[0 0 0],...
                'BusyAction','queue',...
                'TooltipString','Coronal slice navigation',...
                'Min',1,'Max',ydim,'SliderStep',slider_step, ...
                'Value',slider_val,...
                'Callback','rri_view_avw([],[],''coronal_slider'');');

      set(handles.coronal_slider,'position',pos);	% linux66
   end

   %  Axial Slider
   %
   x = front_pos(1) + front_pos(3);
   y = front_pos(2);
   w = side_pos(1) - x;
   h = front_pos(4);

   pos = [x y w h];

   if zdim > 1,
      slider_step(1) = 1/(zdim);
      slider_step(2) = 1.00001/(zdim);

      handles.axial_slider = uicontrol('Parent',GUI, ...
                'Style','slider','Units','Normalized', Font, ...
                'Position',pos, 'HorizontalAlignment','center',...
                'BackgroundColor',[0.5 0.5 0.5],'ForegroundColor',[0 0 0],...
                'BusyAction','queue',...
                'TooltipString','Axial slice navigation',...
                'Min',1,'Max',zdim,'SliderStep',slider_step, ...
                'Value',AVWVIEW.slices.axi,...
                'Callback','rri_view_avw([],[],''axial_slider'');');

      set(handles.axial_slider,'position',pos);	% linux66
   end

   %  plot info view
   %
   info_pos = [side_pos([1,3]); top_pos([2,4])];
   info_pos = info_pos(:);

   num_inputline = 10;
   inputline_space =info_pos(4) / num_inputline;

   %  Origin Position
   %
   x = info_pos(1);
   y = info_pos(2);
   w = info_pos(3)*0.5;
   h = inputline_space*0.6;

   pos = [x y w h];

   handles.Torigin = uicontrol('Parent',GUI,'Style','text', ...
        'Units','Normalized', Font, ...
        'Position',pos, 'HorizontalAlignment', 'left',...
        'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
        'BusyAction','queue',...
        'String','Origin Position (XYZ):');

   x = x + w;
   w = info_pos(3)*0.5;

   pos = [x y w h];

   handles.origin = uicontrol('Parent',GUI,'Style','text', ...
        'Units','Normalized', Font, ...
        'Position',pos, 'HorizontalAlignment', 'right',...
        'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
        'BusyAction','queue',...
        'String','','Value',[0 0 0]);

   %  Image Position at Mouse Click
   %
   x = info_pos(1);
   y = y + inputline_space;
   w = info_pos(3)*0.5;

   pos = [x y w h];

   handles.Timpos = uicontrol('Parent',GUI,'Style','text', ...
        'Units','Normalized', Font, ...
        'Position',pos, 'HorizontalAlignment', 'left',...
        'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
        'BusyAction','queue',...
        'String','Image Position (XYZ):');

   x = x + w + 0.005;
   y = y - 0.008;
   w = info_pos(3)*0.5;
   h = inputline_space*0.9;

   pos = [x y w h];

   handles.impos = uicontrol('Parent',GUI,'Style','edit', ...
        'Units','Normalized', Font, ...
        'Position',pos, 'HorizontalAlignment', 'right',...
        'BackgroundColor', [1 1 1], 'ForegroundColor', [0 0 0],...
        'BusyAction','queue',...
        'Callback','rri_view_avw([],[],''impos_edit'');', ...
        'String','','Value',[0 0 0]);

   %  Image Intensity Value at Mouse Click
   %
   x = info_pos(1);
   y = y + inputline_space;
   w = info_pos(3)*0.5;
   h = inputline_space*0.6;

   pos = [x y w h];

   handles.Timval = uicontrol('Parent',GUI,'Style','text', ...
      'Units','Normalized', Font, ...
      'Position',pos, 'HorizontalAlignment', 'left',...
      'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
      'BusyAction','queue',...
      'String','Image Intensity:');

   x = x + w;
   w = info_pos(3)*0.5;

   pos = [x y w h];

   handles.imval = uicontrol('Parent',GUI,'Style','text', ...
      'Units','Normalized', Font, ...
      'Position',pos, 'HorizontalAlignment', 'right',...
      'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
      'BusyAction','queue',...
      'String',' ');

   %  Voxel Unit
   %
   x = info_pos(1);
   y = y + inputline_space;
   w = info_pos(3)*0.7;

   pos = [x y w h];

   handles.Tcoord = uicontrol('Parent',GUI,'Style','text', ...
      'Units','Normalized', Font, ...
      'Position',pos, 'HorizontalAlignment', 'left',...
      'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
      'BusyAction','queue',...
      'String','Voxel Unit:');

   x = x + w;
   w = info_pos(3)*0.3;

   pos = [x y w h];

   handles.coord = uicontrol('Parent',GUI,'Style','popupmenu', ...
      'Units','Normalized', Font, ...
      'Position',pos, ...
      'BackgroundColor', [1 1 1], 'ForegroundColor', [0 0 0],...
      'BusyAction','queue',...
      'TooltipString','Voxel or Mensurated Axis Coordinates',...
      'String',{'Voxel','Millimeter'},...
      'Callback','rri_view_avw([],[],''coordinates'');');

   %  Crosshair
   %
   x = info_pos(1);
   y = y + inputline_space;
   w = info_pos(3)*0.4;

   pos = [x y w h];

   handles.Txhair = uicontrol('Parent',GUI,'Style','text', ...
      'Units','Normalized', Font, ...
      'Position',pos, 'HorizontalAlignment', 'left',...
      'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
      'BusyAction','queue',...
      'String','Crosshair:');

   x = info_pos(1) + info_pos(3)*0.5;
   w = info_pos(3)*0.2;
   h = inputline_space*0.7;

   pos = [x y w h];

   Font.FontSize   = 8;

   handles.xhair_color = uicontrol('Parent',GUI,'Style','push', ...
      'Units','Normalized', Font, ...
      'Position',pos, 'HorizontalAlignment', 'center',...
      'TooltipString','Crosshair Color',...
      'User',[1 0 0],...
      'String','Color',...
      'Callback','rri_view_avw([],[],''xhair_color'');');

%   x = x + w;
   x = info_pos(1) + info_pos(3)*0.7;
   w = info_pos(3)*0.3;

   pos = [x y w h];

   Font.FontSize   = 12;

   handles.xhair = uicontrol('Parent',GUI,'Style','popupmenu', ...
      'Units','Normalized', Font, ...
      'Position',pos, ...
      'BackgroundColor', [1 1 1], 'ForegroundColor', [0 0 0],...
      'BusyAction','queue',...
      'TooltipString','Display or Hide Crosshair',...
      'String',{'On','Off'},...
      'Callback','rri_view_avw([],[],''crosshair'');');

   %  Histogram & Color
   %
   x = info_pos(1);
   w = info_pos(3)*0.45;
   h = inputline_space * 1.5;

   pos = [x,  y+inputline_space*0.8,  w,  h];

   handles.hist_frame = uicontrol('Parent',GUI, ...	
   	'Units','normal', ...
   	'BackgroundColor',[0.8 0.8 0.8], ...
   	'Position',pos, ...
   	'Style','frame');

   x = info_pos(1) + info_pos(3)*0.475;
   w = info_pos(3)*0.55;
   h = inputline_space * 1.5;

   pos = [x,  y+inputline_space*0.8,  w,  h];

   handles.color_frame = uicontrol('Parent',GUI, ...	
   	'Units','normal', ...
   	'BackgroundColor',[0.8 0.8 0.8], ...
   	'Position',pos, ...
   	'Style','frame');

   x = info_pos(1) + info_pos(3)*0.025;
   y = y + inputline_space;
   w = info_pos(3)*0.2;
   h = inputline_space*0.7;

   pos = [x y w h];

   Font.FontSize   = 8;

   handles.hist_eq = uicontrol('Parent',GUI,'Style','toggle', ...
      'Units','Normalized', Font, ...
      'Position',pos, 'HorizontalAlignment', 'center',...
      'TooltipString','Histogram Equalization',...
      'String','Hist EQ',...
      'Callback','rri_view_avw([],[],''hist_eq'');');

   x = x + w;
   w = info_pos(3)*0.2;

   pos = [x y w h];

   handles.hist_plot = uicontrol('Parent',GUI,'Style','push', ...
      'Units','Normalized', Font, ...
      'Position',pos, 'HorizontalAlignment', 'center',...
      'TooltipString','Histogram Plot',...
      'String','Hist Plot',...
      'Callback','rri_view_avw([],[],''hist_plot'');');

   x = info_pos(1) + info_pos(3)*0.5;
   w = info_pos(3)*0.2;

   pos = [x y w h];

   handles.neg_color = uicontrol('Parent',GUI,'Style','toggle', ...
      'Units','Normalized', Font, ...
      'Position',pos, 'HorizontalAlignment', 'center',...
      'TooltipString','Negative Colormap',...
      'String','Negative',...
      'Callback','rri_view_avw([],[],''neg_color'');');

   x = info_pos(1) + info_pos(3)*0.7;
   w = info_pos(3)*0.3;

   pos = [x y w h];

   Font.FontSize   = 12;

   handles.color = uicontrol('Parent',GUI,'Style','popupmenu', ...
      'Units','Normalized', Font, ...
      'Position',pos, ...
      'BackgroundColor', [1 1 1], 'ForegroundColor', [0 0 0],...
      'BusyAction','queue',...
      'TooltipString','Change Colormap',...
      'String',{'Gray','Bone','Copper','Pink','Cool','Hot','Jet'},...
      'Callback','rri_view_avw([],[],''color'');');

   x = info_pos(1) + info_pos(3)*0.1;
   y = y + inputline_space;
   w = info_pos(3)*0.28;
   h = inputline_space*0.6;

   pos = [x y w h];

   handles.Thist = uicontrol('Parent',GUI,'Style','text', ...
      'Units','Normalized', Font, ...
      'Position',pos, 'HorizontalAlignment', 'center',...
      'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
      'BusyAction','queue',...
      'String','Histogram');

   x = info_pos(1) + info_pos(3)*0.57;
   w = info_pos(3)*0.35;

   pos = [x y w h];

   handles.Tcolor = uicontrol('Parent',GUI,'Style','text', ...
      'Units','Normalized', Font, ...
      'Position',pos, 'HorizontalAlignment', 'center',...
      'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
      'BusyAction','queue',...
      'String','Color Mapping');

   %  Contrast Frame
   %
   x = info_pos(1);
   w = info_pos(3)*0.45;
   h = inputline_space * 2;

   pos = [x,  y+inputline_space*0.8,  w,  h];

   handles.contrast_frame = uicontrol('Parent',GUI, ...	
   	'Units','normal', ...
   	'BackgroundColor',[0.8 0.8 0.8], ...
   	'Position',pos, ...
   	'Style','frame');

   %  Brightness Frame
   %
   x = info_pos(1) + info_pos(3)*0.475;
   w = info_pos(3)*0.55;

   pos = [x,  y+inputline_space*0.8,  w,  h];

   handles.brightness_frame = uicontrol('Parent',GUI, ...	
   	'Units','normal', ...
   	'BackgroundColor',[0.8 0.8 0.8], ...
   	'Position',pos, ...
   	'Style','frame');

   %  Contrast
   %
   x = info_pos(1) + info_pos(3)*0.025;
   y = y + inputline_space;
   w = info_pos(3)*0.4;
   h = inputline_space*0.6;

   pos = [x y w h];

   Font.FontSize   = 12;

   slider_step(1) = 5/250;
   slider_step(2) = 5.00001/250;

   handles.contrast = uicontrol('Parent',GUI, ...
      'Style','slider','Units','Normalized', Font, ...
      'Position',pos, 'HorizontalAlignment', 'left',...
      'BackgroundColor',[0.5 0.5 0.5],'ForegroundColor',[0 0 0],...
      'BusyAction','queue',...
      'TooltipString','Change contrast',...
      'Min',1,'Max',251,'SliderStep',slider_step, ...
      'Value',1, ...
      'Callback','rri_view_avw([],[],''contrast'');');

   set(handles.contrast,'position',pos);	% linux66

   %  Brightness
   %
   x = info_pos(1) + info_pos(3)*0.5;
   w = info_pos(3)*0.5;

   pos = [x y w h];

   Font.FontSize   = 12;

   slider_step(1) = 1/50;
   slider_step(2) = 1.00001/50;

   handles.brightness = uicontrol('Parent',GUI, ...
      'Style','slider','Units','Normalized', Font, ...
      'Position',pos, 'HorizontalAlignment', 'left',...
      'BackgroundColor',[0.5 0.5 0.5],'ForegroundColor',[0 0 0],...
      'BusyAction','queue',...
      'TooltipString','Change brightness',...
      'Min',-1,'Max',1,'SliderStep',slider_step, ...
      'Value',0, ...
      'Callback','rri_view_avw([],[],''brightness'');');

   set(handles.brightness,'position',pos);	% linux66

   %  Contrast
   %
   x = info_pos(1) + info_pos(3)*0.025;
   y = y + inputline_space;
   w = info_pos(3)*0.22;

   pos = [x y w h];

   handles.Tcontrast = uicontrol('Parent',GUI,'Style','text', ...
      'Units','Normalized', Font, ...
      'Position',pos, 'HorizontalAlignment', 'left',...
      'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
      'BusyAction','queue',...
      'String','Contrast:');

   x = x + w;
   w = info_pos(3)*0.18;

   pos = [x y w h];

   Font.FontSize   = 8;

   handles.contrast_def = uicontrol('Parent',GUI,'Style','push', ...
      'Units','Normalized', Font, ...
      'Position',pos, 'HorizontalAlignment', 'center',...
      'TooltipString','Restore initial contrast',...
      'String','Reset',...
      'Callback','rri_view_avw([],[],''contrast_def'');');

   %  Brightness
   %
   x = info_pos(1) + info_pos(3)*0.5;
   w = info_pos(3)*0.32;

   pos = [x y w h];

   Font.FontSize   = 12;

   handles.Tbrightness = uicontrol('Parent',GUI,'Style','text', ...
      'Units','Normalized', Font, ...
      'Position',pos, 'HorizontalAlignment', 'left',...
      'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
      'BusyAction','queue',...
      'String','Brightness:');

   x = x + w;
   w = info_pos(3)*0.18;

   pos = [x y w h];

   Font.FontSize   = 8;

   handles.brightness_def = uicontrol('Parent',GUI,'Style','push', ...
      'Units','Normalized', Font, ...
      'Position',pos, 'HorizontalAlignment', 'center',...
      'TooltipString','Restore initial brightness',...
      'String','Reset',...
      'Callback','rri_view_avw([],[],''brightness_def'');');

   %  init image handles
   %
   handles.axial_image = 0;
   handles.coronal_image = 0;
   handles.sagittal_image = 0;

   %  plot axial view
   %
   img_slice = squeeze(avw.img(:,:,AVWVIEW.slices.axi));
   h1 = plot_view(GUI, xdim, ydim, top_ax, img_slice', clim);
   set(h1,'buttondown','rri_view_avw([],[],''axial_image'');');
   handles.axial_image = h1;
   handles.axial_axes = top_ax;

   %  plot coronal view
   %
   img_slice = squeeze(avw.img(:,AVWVIEW.slices.cor,:));
   h1 = plot_view(GUI, xdim, zdim, front_ax, img_slice', clim);
   set(h1,'buttondown','rri_view_avw([],[],''coronal_image'');');
   handles.coronal_image = h1;
   handles.coronal_axes = front_ax;

   %  plot sagittal view
   %
   if isrhos
      img_slice = squeeze(avw.img(xdim-AVWVIEW.slices.sag+1,:,:));
   else
      img_slice = squeeze(avw.img(AVWVIEW.slices.sag,:,:));
   end
   h1 = plot_view(GUI, ydim, zdim, side_ax, img_slice', clim);
   set(h1,'buttondown','rri_view_avw([],[],''sagittal_image'');');
   set(side_ax,'Xdir', 'reverse');
   handles.sagittal_image = h1;
   handles.sagittal_axes = side_ax;

   %  Update the gui_struct handles for this gui
   %
   AVWVIEW.handles = handles;			% gui handles
   AVWVIEW.isrhos = isrhos;			% right handed orientation system
   AVWVIEW.butt_down_cmd = butt_down_cmd;	% command after button down click

   AVWVIEW = set_coordinates(AVWVIEW);		% coord unit

   if ~isfield(AVWVIEW, 'axi_xhair') |  ...
      ~isfield(AVWVIEW, 'cor_xhair') |  ...
      ~isfield(AVWVIEW, 'sag_xhair')

      AVWVIEW.axi_xhair = [];			% top cross hair
      AVWVIEW.cor_xhair = [];			% front cross hair
      AVWVIEW.sag_xhair = [];			% side cross hair

   end

   update_AVWVIEW(AVWVIEW);

   return;						% init


%----------------------------------------------------------------
function GUI = update_img(img, gui3view)

   GUI = gui3view.figure;
   AVWVIEW = getappdata(GUI,'AVWVIEW');
   gui3view.area = AVWVIEW.area;

   switch double(AVWVIEW.avw.hdr.dime.bitpix)
   case 1
      AVWVIEW.avw.img = uint8(img);		% binary
   case 8
      AVWVIEW.avw.img = uint8(img);		% unsigned char
   case 16
      AVWVIEW.avw.img = int16(img);		% signed short
   case 32
      AVWVIEW.avw.img = int32(img);		% signed integer
   case 64
      AVWVIEW.avw.img = double(img);		% double
   otherwise
      msgbox('Incorrect image header');
      return;
   end

   clim = double([min(AVWVIEW.avw.img(:)) max(AVWVIEW.avw.img(:))]);

   if clim(1) == clim(2)
      clim(2) = clim(1) + 0.000001;
   end

   Saxi = squeeze(AVWVIEW.avw.img(:,:,AVWVIEW.slices.axi));
   set(AVWVIEW.handles.axial_axes,'CLim',clim);
   set(AVWVIEW.handles.axial_image,'CData',Saxi'); drawnow;

   Scor = squeeze(AVWVIEW.avw.img(:,AVWVIEW.slices.cor,:));
   set(AVWVIEW.handles.coronal_axes,'CLim',clim);
   set(AVWVIEW.handles.coronal_image,'CData',Scor'); drawnow;

   if AVWVIEW.isrhos
      Ssag = ...
	squeeze(AVWVIEW.avw.img(size(AVWVIEW.avw.img,1)-AVWVIEW.slices.sag+1,:,:));
   else
      Ssag = squeeze(AVWVIEW.avw.img(AVWVIEW.slices.sag,:,:));
   end
   set(AVWVIEW.handles.sagittal_axes,'CLim',clim);
   set(AVWVIEW.handles.sagittal_image,'CData',Ssag'); drawnow;

   update_AVWVIEW(AVWVIEW);

   return;						% update_img


%----------------------------------------------------------------
function GUI = update_avw(avw, gui3view, isrhos, impos_init, butt_down_cmd)

   GUI = gui3view.figure;
   AVWVIEW = getappdata(GUI,'AVWVIEW');
   gui3view.area = AVWVIEW.area;

   %  store old value
   %
   coord_val = get(AVWVIEW.handles.coord, 'value');
   xhair_val = get(AVWVIEW.handles.xhair, 'value');
   color_map_val = get(AVWVIEW.handles.color,'value');
   brightness = get(AVWVIEW.handles.brightness,'value');
   contrast = round(get(AVWVIEW.handles.contrast,'value'));
   hist_eq_val = get(AVWVIEW.handles.hist_eq,'value');

   %  remove existing plot
   %
   delete(AVWVIEW.handles.sagittal_slider);
   delete(AVWVIEW.handles.coronal_slider);
   delete(AVWVIEW.handles.axial_slider);
   delete(AVWVIEW.handles.Torigin);
   delete(AVWVIEW.handles.origin);
   delete(AVWVIEW.handles.Timpos);
   delete(AVWVIEW.handles.impos);
   delete(AVWVIEW.handles.Timval);
   delete(AVWVIEW.handles.imval);
   delete(AVWVIEW.handles.Tcoord);
   delete(AVWVIEW.handles.coord);
   delete(AVWVIEW.handles.Txhair);
   delete(AVWVIEW.handles.xhair_color);
   delete(AVWVIEW.handles.xhair);
   delete(AVWVIEW.handles.hist_frame);
   delete(AVWVIEW.handles.color_frame);
   delete(AVWVIEW.handles.hist_eq);
   delete(AVWVIEW.handles.hist_plot);
   delete(AVWVIEW.handles.neg_color);
   delete(AVWVIEW.handles.color);
   delete(AVWVIEW.handles.Thist);
   delete(AVWVIEW.handles.Tcolor);
   delete(AVWVIEW.handles.Tcontrast);
   delete(AVWVIEW.handles.contrast_def);
   delete(AVWVIEW.handles.contrast);
   delete(AVWVIEW.handles.contrast_frame);
   delete(AVWVIEW.handles.Tbrightness);
   delete(AVWVIEW.handles.brightness_def);
   delete(AVWVIEW.handles.brightness);
   delete(AVWVIEW.handles.brightness_frame);

   rri_view_avw(avw, gui3view, 'init', isrhos, impos_init, butt_down_cmd);
   AVWVIEW = getappdata(GUI,'AVWVIEW');
   set(AVWVIEW.handles.coord, 'value', coord_val);
   set(AVWVIEW.handles.xhair, 'value', xhair_val);
   set(AVWVIEW.handles.color,'value',color_map_val);
   set(AVWVIEW.handles.brightness,'value',brightness);
   set(AVWVIEW.handles.contrast,'value',contrast);
   set(AVWVIEW.handles.hist_eq,'value',hist_eq_val)

   rri_view_avw([], gui3view, 'coordinates');
   rri_view_avw([], gui3view, 'crosshair');

   change_color_map(GUI);
   hist_eq(GUI);

   return;						% update_avw


%----------------------------------------------------------------
function [top_ax, front_ax, side_ax] = create_ax(GUI, area, vol_size)

   cur_fig = gcf;			% save h_wait fig
   figure(GUI);

   set(GUI,'unit','pixel');
   fig_pos = get(GUI,'position');

   gap_x = 15/fig_pos(3);		% width of vertical scrollbar
   gap_y = 15/fig_pos(4);		% width of horizontal scrollbar

   a = (area(3) - gap_x) * fig_pos(3) / (vol_size(1) + vol_size(2));
   b = (area(4) - gap_y) * fig_pos(4) / (vol_size(2) + vol_size(3));
   a = min([a b]);			% make sure 'ax' is inside 'area'

   top_w = vol_size(1) * a / fig_pos(3);
   side_w = vol_size(2) * a / fig_pos(3);
   top_h = vol_size(2) * a / fig_pos(4);
   side_h = vol_size(3) * a / fig_pos(4);
   side_x = area(1) + top_w + gap_x;
   side_y = area(2) + top_h + gap_y;

   set(GUI,'unit','normal');

   top_pos = [area(1) area(2) top_w top_h];
   front_pos = [area(1) side_y top_w side_h];
   side_pos = [side_x side_y side_w side_h];

   AVWVIEW = getappdata(GUI, 'AVWVIEW');

   if isempty(AVWVIEW)
      top_ax = axes('position', top_pos);
      front_ax = axes('position', front_pos);
      side_ax = axes('position', side_pos);
   else
      top_ax = AVWVIEW.handles.axial_axes;
      front_ax = AVWVIEW.handles.coronal_axes;
      side_ax = AVWVIEW.handles.sagittal_axes;

      set(top_ax, 'position', top_pos);
      set(front_ax, 'position', front_pos);
      set(side_ax, 'position', side_pos);
   end

   figure(cur_fig);

   return;						% create_ax


%----------------------------------------------------------------
function h1 = plot_view(GUI, x, y, img_ax, img_slice, clim)

   h1 = [];

   if x > 1 & y > 1,

      axes(img_ax);

      AVWVIEW = getappdata(GUI, 'AVWVIEW');

      if isempty(AVWVIEW)
         h1 = imagesc(img_slice,clim);
      else
         h1 = AVWVIEW.handles.axial_image;

         if ~isequal(get(h1,'parent'), img_ax)
            h1 = AVWVIEW.handles.coronal_image;
         end

         if ~isequal(get(h1,'parent'), img_ax)
            h1 = AVWVIEW.handles.sagittal_image;
         end

         set(h1, 'cdata', img_slice); drawnow;
         set(h1, 'xdata', size(img_slice,2));
         set(h1, 'ydata', size(img_slice,1));
      end

      set(GUI, 'colormap', gray(256));

      set(img_ax,'YDir','normal','XLimMode','manual','YLimMode','manual',...
         'ClimMode','manual','YColor',[0 0 0],'XColor',[0 0 0], ...
         'xtick',[],'ytick',[], 'clim', clim);

   end

   return;						% plot_view


%----------------------------------------------------------------
function AVWVIEW = set_coordinates(AVWVIEW)

    imgPlim.voxels = AVWVIEW.dims;
    imgNlim.voxels = [1 1 1];
    
    xdata = [imgNlim.voxels(1) imgPlim.voxels(1)];
    ydata = [imgNlim.voxels(2) imgPlim.voxels(2)];
    zdata = [imgNlim.voxels(3) imgPlim.voxels(3)];
    
    if isfield(AVWVIEW.handles,'axial_image'), 
        set(AVWVIEW.handles.axial_axes,'Xlim',xdata);
        set(AVWVIEW.handles.axial_axes,'Ylim',ydata);
        set(AVWVIEW.handles.axial_axes,'Zlim',zdata);
        set(AVWVIEW.handles.axial_image,'Xdata',xdata);
        set(AVWVIEW.handles.axial_image,'Ydata',ydata);
    end;
    if isfield(AVWVIEW.handles,'coronal_image'),
        set(AVWVIEW.handles.coronal_axes,'Xlim',xdata);
        set(AVWVIEW.handles.coronal_axes,'Ylim',zdata);
        set(AVWVIEW.handles.coronal_axes,'Zlim',ydata);
        set(AVWVIEW.handles.coronal_image,'Xdata',xdata);
        set(AVWVIEW.handles.coronal_image,'Ydata',zdata);
    end;
    if isfield(AVWVIEW.handles,'sagittal_image'),
        set(AVWVIEW.handles.sagittal_axes,'Xlim',ydata);
        set(AVWVIEW.handles.sagittal_axes,'Ylim',zdata);
        set(AVWVIEW.handles.sagittal_axes,'Zlim',xdata);
        set(AVWVIEW.handles.sagittal_image,'Xdata',ydata);
        set(AVWVIEW.handles.sagittal_image,'Ydata',zdata);
    end;

    return						% set_coordinates


%----------------------------------------------------------------
function set_image_value(AVWVIEW),

    % get coordinates of selected voxel and the image intensity there

    if AVWVIEW.isrhos    
       sag = AVWVIEW.dims(1) - round(AVWVIEW.slices.sag) + 1;
    else
       sag = round(AVWVIEW.slices.sag);
    end

    cor = round(AVWVIEW.slices.cor);
    axi = round(AVWVIEW.slices.axi);

    if isfield(AVWVIEW, 'disp')
       img = AVWVIEW.disp;    
    else
       img = AVWVIEW.avw.img;
    end

    imgvalue = double(img(sag,cor,axi));

    set(AVWVIEW.handles.imval,'String',sprintf('%7.0f',imgvalue));
    set(AVWVIEW.handles.imval,'Value',imgvalue);

    % Now update the coordinates of the selected voxel

    AVWVIEW = update_imgXYZ(AVWVIEW);

    if get(AVWVIEW.handles.coord,'value') == 1,
       sag = AVWVIEW.imgXYZ.voxels(1);
       cor = AVWVIEW.imgXYZ.voxels(2);
       axi = AVWVIEW.imgXYZ.voxels(3);
       org = AVWVIEW.origin;
    elseif get(AVWVIEW.handles.coord,'value') == 2,
       sag = AVWVIEW.imgXYZ.mm(1);
       cor = AVWVIEW.imgXYZ.mm(2);
       axi = AVWVIEW.imgXYZ.mm(3);
       org = [0 0 0];
    end

    set(AVWVIEW.handles.impos,'Value',[sag,cor,axi]);

    if AVWVIEW.isrhos
       tmp = sag;
       sag = cor;
       cor = tmp;
       org = org([2 1 3]);
    end

    if get(AVWVIEW.handles.coord,'value') == 1,
        string = sprintf('%7.0f %7.0f %7.0f',sag,cor,axi);
        org_str = sprintf('%7.0f %7.0f %7.0f', org(1), org(2), org(3));
    elseif get(AVWVIEW.handles.coord,'value') == 2,
        string = sprintf('%7.1f %7.1f %7.1f',sag,cor,axi);
        org_str = sprintf('%7.1f %7.1f %7.1f', org(1), org(2), org(3));
    end;
    
    set(AVWVIEW.handles.impos,'String',string);
    set(AVWVIEW.handles.origin, 'string', org_str);

    return						% set_image_value


%----------------------------------------------------------------
function AVWVIEW = get_slice_position(AVWVIEW,view),

    %  obtain slices that is in correct unit, then update slices
    %
    slices = AVWVIEW.slices;
	
    switch view,
    case 'sag',
        currentpoint = get(AVWVIEW.handles.sagittal_axes,'CurrentPoint');
        slices.cor = currentpoint(1,1);
        slices.axi = currentpoint(1,2);
    case 'cor',
        currentpoint = get(AVWVIEW.handles.coronal_axes,'CurrentPoint');
        slices.sag = currentpoint(1,1);
        slices.axi = currentpoint(1,2);
    case 'axi',
        currentpoint = get(AVWVIEW.handles.axial_axes,'CurrentPoint');
        slices.sag = currentpoint(1,1);
        slices.cor = currentpoint(1,2);
    end

    %  update AVWVIEW.slices with the updated slices
    %    
    AVWVIEW.slices.axi = round(slices.axi);
    AVWVIEW.slices.cor = round(slices.cor);
    AVWVIEW.slices.sag = round(slices.sag);

    return						% get_slice_position


%----------------------------------------------------------------
function AVWVIEW = get_slider_position(AVWVIEW),

    [AVWVIEW.slices.sag,AVWVIEW.slices.cor,AVWVIEW.slices.axi] = deal(0);
    
    if isfield(AVWVIEW.handles,'sagittal_slider'),
        if ishandle(AVWVIEW.handles.sagittal_slider),
            AVWVIEW.slices.sag = ...
		round(get(AVWVIEW.handles.sagittal_slider,'Value'));
        end

        if AVWVIEW.isrhos
           AVWVIEW.slices.sag = AVWVIEW.dims(1) - AVWVIEW.slices.sag + 1;
        end
    end
    
    if isfield(AVWVIEW.handles,'coronal_slider'),
        if ishandle(AVWVIEW.handles.coronal_slider),
            AVWVIEW.slices.cor = ...
		round(AVWVIEW.dims(2) - ...
		get(AVWVIEW.handles.coronal_slider,'Value') + 1);
        end
    end
    
    if isfield(AVWVIEW.handles,'axial_slider'),
        if ishandle(AVWVIEW.handles.axial_slider),
            AVWVIEW.slices.axi = ...
		round(get(AVWVIEW.handles.axial_slider,'Value'));
        end
    end

    return						% get_slider_position


%----------------------------------------------------------------
function AVWVIEW = update_imgXYZ(AVWVIEW),

   AVWVIEW.imgXYZ.voxels = ...
	[AVWVIEW.slices.sag,AVWVIEW.slices.cor,AVWVIEW.slices.axi];
   AVWVIEW.imgXYZ.mm = ...
	(AVWVIEW.imgXYZ.voxels - AVWVIEW.origin) .* AVWVIEW.voxel_size;

   return						% update_imgXYZ


%----------------------------------------------------------------
function AVWVIEW = convert2voxel(AVWVIEW,slices),

    if get(AVWVIEW.handles.coord,'value') == 1,
        % voxels
        AVWVIEW.slices.axi = round(slices.axi);
        AVWVIEW.slices.cor = round(slices.cor);
        AVWVIEW.slices.sag = round(slices.sag);
    elseif get(AVWVIEW.handles.coord,'value') == 2,
        % using mm
        xpix = AVWVIEW.voxel_size(1);
        ypix = AVWVIEW.voxel_size(2);
        zpix = AVWVIEW.voxel_size(3);

        AVWVIEW.slices.axi = round(slices.axi / zpix + AVWVIEW.origin(3));
        AVWVIEW.slices.cor = round(slices.cor / ypix + AVWVIEW.origin(2));
        AVWVIEW.slices.sag = round(slices.sag / xpix + AVWVIEW.origin(1));
    end

    return						% convert2voxel


%----------------------------------------------------------------
function AVWVIEW = check_slices(AVWVIEW),

    if isfield(AVWVIEW, 'disp')
       img = AVWVIEW.disp;    
    else
       img = AVWVIEW.avw.img;
    end
    
    [ SagSize, CorSize, AxiSize ] = size(img);
    if AVWVIEW.slices.sag > SagSize, AVWVIEW.slices.sag = SagSize; end;
    if AVWVIEW.slices.sag < 1, AVWVIEW.slices.sag = 1; end;
    if AVWVIEW.slices.cor > CorSize, AVWVIEW.slices.cor = CorSize; end;
    if AVWVIEW.slices.cor < 1, AVWVIEW.slices.cor = 1; end;
    if AVWVIEW.slices.axi > AxiSize, AVWVIEW.slices.axi = AxiSize; end;
    if AVWVIEW.slices.axi < 1, AVWVIEW.slices.axi = 1; end;
    
    return						% check_slices


%----------------------------------------------------------------
function AVWVIEW = update_AVWVIEW(AVWVIEW)

   %  add imgXYZ into AVWVIEW struct
   %
   AVWVIEW = check_slices(AVWVIEW);
   AVWVIEW = update_imgXYZ(AVWVIEW);

   %  update xhair
   %
   p_axi = AVWVIEW.imgXYZ.voxels([1 2]);
   p_cor = AVWVIEW.imgXYZ.voxels([1 3]);
   p_sag = AVWVIEW.imgXYZ.voxels([2 3]);

   if AVWVIEW.isrhos
      xlim = get(AVWVIEW.handles.axial_image, 'xdata');
      p_axi(1) = xlim(2) - (p_axi(1) - xlim(1));
      p_cor(1) = xlim(2) - (p_cor(1) - xlim(1));
   end

   AVWVIEW.axi_xhair = ...
	rri_xhair(p_axi, AVWVIEW.axi_xhair, AVWVIEW.handles.axial_axes);

   AVWVIEW.cor_xhair = ...
	rri_xhair(p_cor, AVWVIEW.cor_xhair, AVWVIEW.handles.coronal_axes);

   AVWVIEW.sag_xhair = ...
	rri_xhair(p_sag, AVWVIEW.sag_xhair, AVWVIEW.handles.sagittal_axes);

   setappdata(AVWVIEW.gui, 'AVWVIEW', AVWVIEW);
   set_image_value(AVWVIEW);

   return;						% update_AVWVIEW


%----------------------------------------------------------------
function change_color_map(fig)

   AVWVIEW = getappdata(fig,'AVWVIEW');

   if isfield(AVWVIEW, 'num_color')
      num_color = AVWVIEW.num_color;
   else
      num_color = 256;
   end

   if isfield(AVWVIEW, 'high_colormap')
      high_colormap = AVWVIEW.high_colormap;
   else
      high_colormap = [];
   end

   high_rownum = size(high_colormap, 1);
   low_colormap_end = num_color - high_rownum;

   color_map_val = get(AVWVIEW.handles.color,'value');
   brightness = get(AVWVIEW.handles.brightness,'value');

   if isempty(high_colormap)
      contrast = (num_color-6)*(get(AVWVIEW.handles.contrast,'value')-1)/250+1;
      contrast = round(contrast);
   else
      contrast = (num_color-6)*(get(AVWVIEW.handles.contrast,'value')-1)/250+1;
      contrast = (low_colormap_end-6)*(contrast-1)/(num_color-6)+1;
      contrast = round(contrast);
   end

   switch color_map_val
   case {1}
      color_map = gray(low_colormap_end - contrast + 1);
   case {2}
      color_map = bone(low_colormap_end - contrast + 1);
   case {3}
      color_map = copper(low_colormap_end - contrast + 1);
   case {4}
      color_map = pink(low_colormap_end - contrast + 1);
   case {5}
      color_map = cool(low_colormap_end - contrast + 1);
   case {6}
      color_map = hot(low_colormap_end - contrast + 1);
   case {7}
      color_map = jet(low_colormap_end - contrast + 1);
   end

   color_map = [zeros(contrast,3); color_map(2:end,:)];

   if get(AVWVIEW.handles.neg_color,'value')
      color_map = flipud(color_map);
   end

   color_map = brighten(color_map, brightness);

   color_map = [color_map; high_colormap];
   set(fig, 'colormap', color_map);

   return;						% change_color_map


%----------------------------------------------------------------
function hist_plot(fig)

   AVWVIEW = getappdata(fig,'AVWVIEW');

   if isfield(AVWVIEW, 'disp')
      img = AVWVIEW.disp;    
   else
      img = AVWVIEW.avw.img;
   end

   img = double(img(:));
   range = max(img) - min(img) + 1;
   figure; hist(img, range);

   set(gca, 'xlim', [-range/5, max(img)]);
   xlabel('Voxel Intensity');
   ylabel('Voxel Numbers for Each Intensity');
   set(gcf, 'NumberTitle','off','Name','Histogram Plot');

   return;						% hist_plot


%----------------------------------------------------------------
function hist_eq(fig)

   AVWVIEW = getappdata(fig,'AVWVIEW');

   old_pointer = get(fig,'Pointer');
   set(fig,'Pointer','watch');

   if get(AVWVIEW.handles.hist_eq,'value')
      max_img = max(double(AVWVIEW.avw.img(:)));
      tmp = double(AVWVIEW.avw.img) / max_img;
      tmp = histeq(tmp(:));
      AVWVIEW.disp = reshape(tmp, size(AVWVIEW.avw.img));
      min_disp = min(AVWVIEW.disp(:));
      AVWVIEW.disp = (AVWVIEW.disp - min_disp);
      AVWVIEW.disp = AVWVIEW.disp * max_img / max(AVWVIEW.disp(:));
   else
      if isfield(AVWVIEW, 'disp')
         AVWVIEW.disp = AVWVIEW.avw.img;
      else
         set(fig,'Pointer',old_pointer);
         return;
      end
   end

   %  update axial view
   %
   img_slice = squeeze(AVWVIEW.disp(:,:,AVWVIEW.slices.axi));
   h1 = AVWVIEW.handles.axial_image;
   set(h1, 'cdata', img_slice'); drawnow;

   %  update coronal view
   %
   img_slice = squeeze(AVWVIEW.disp(:,AVWVIEW.slices.cor,:));
   h1 = AVWVIEW.handles.coronal_image;
   set(h1, 'cdata', img_slice'); drawnow;

   %  update sagittal view
   %
   if AVWVIEW.isrhos
      img_slice = squeeze(AVWVIEW.disp(size(AVWVIEW.disp,1)-AVWVIEW.slices.sag+1,:,:));
   else
      img_slice = squeeze(AVWVIEW.disp(AVWVIEW.slices.sag,:,:));
   end
   h1 = AVWVIEW.handles.sagittal_image;
   set(h1, 'cdata', img_slice'); drawnow;

   %  remove disp field if un-check 'histeq' button
   %
   if ~get(AVWVIEW.handles.hist_eq,'value') & isfield(AVWVIEW, 'disp')
      AVWVIEW = rmfield(AVWVIEW, 'disp');
   end

   update_AVWVIEW(AVWVIEW);

   set(fig,'Pointer',old_pointer);

   return;						% hist_eq


%----------------------------------------------------------------
function change_xhair_coordinates(fig)

   AVWVIEW = getappdata(fig,'AVWVIEW');

   axi_img = AVWVIEW.handles.axial_image;
   cor_img = AVWVIEW.handles.coronal_image;
   sag_img = AVWVIEW.handles.sagittal_image;
   imgXYZ = AVWVIEW.imgXYZ;
   xyz = imgXYZ.voxels;

   axi_xlim = get(axi_img, 'xdata');
   axi_ylim = get(axi_img, 'ydata');
   cor_xlim = get(cor_img, 'xdata');
   cor_ylim = get(cor_img, 'ydata');
   sag_xlim = get(sag_img, 'xdata');
   sag_ylim = get(sag_img, 'ydata');

   if isfield(AVWVIEW,'axi_xhair') & ~isempty(AVWVIEW.axi_xhair) ...
      & ishandle(AVWVIEW.axi_xhair.lx)

      axi_lx = AVWVIEW.axi_xhair.lx;
      axi_ly = AVWVIEW.axi_xhair.ly;
      cor_lx = AVWVIEW.cor_xhair.lx;
      cor_ly = AVWVIEW.cor_xhair.ly;
      sag_lx = AVWVIEW.sag_xhair.lx;
      sag_ly = AVWVIEW.sag_xhair.ly;

      set(axi_lx,'xdata', axi_xlim, 'ydata', [xyz(2) xyz(2)]);
      set(axi_ly,'xdata', [xyz(1) xyz(1)], 'ydata', axi_ylim);
      set(cor_lx,'xdata', cor_xlim, 'ydata', [xyz(3) xyz(3)]);
      set(cor_ly,'xdata', [xyz(1) xyz(1)], 'ydata', cor_ylim);
      set(sag_lx,'xdata', sag_xlim, 'ydata', [xyz(3) xyz(3)]);
      set(sag_ly,'xdata', [xyz(2) xyz(2)], 'ydata', sag_ylim);
   end

   return;						% change_xhair_coordinates

