function lyngby_image(S, arg1, arg2, arg3, arg4, arg5, arg6, arg7, ...
    arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, ...
    arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26)

% lyngby_image         - Plot a slice
%
%       function lyngby_image(S, 'PropertyName', 'PropertyValue')
%
%       Input:    S          The slice as a matrix
%     
%       Property: Back       Background slice (anatomical scan)
%                 BackType   [ {None} | Contour | Overwrite | Both } 
%                            Type of merge between background image
%                            and front image
%                 Colorbar   [ {1} true | 0 ] Colorbar shown
%                 Colormap   Colormap (Mx3 matrix)
%                 Contour    Contour slice
%                 Mask       Mask slice
%                 MaskLevel  {0.95} Masking Level
%                 MaskLevelType   [ {fratile} | absolute ]
%                 MaskType   [ {None} | > | >< | == | < ]
%                 Range      Maximum and minimum range for the
%                            colormap. Default set to 
%                            [ min(S(:)) max(S(:)) ] 
%                 XLabel     { 1:size(S,2) } x axis labels
%                 YLabel     { 1:size(S,2) } y axis labels
%
%       Plot a slice with options of a background and masking of the
%       front image.
%
%       See also LYNGBY, LYNGBY_GETSLICE, LYNGBY_UI_VIEW.
%
% $Id: lyngby_image.m,v 1.22 2002/12/18 00:11:56 fnielsen Exp $


    lyngby_ui_option

    % Default properties
    xlabel = 1:size(S,1);
    ylabel = 1:size(S,2);
    colmap = colormap;
    scale = 1;
    Back = zeros(size(S));
    Contour = zeros(size(S));
    backType = 0;
    Mask = ones(size(S));
    maskType = 'none';
    maskLevel = 0.95;
    maskLevelType = 1;
    bColorbar = 1;
    range = [];
    
    % Parse Properties
    n = 1;
    while n <= nargin-2
      eval(sprintf('arg = lower(arg%d);', n));
      if strcmp(arg, 'xlabel')
	n = n + 1;
	eval(sprintf('arg = arg%d;', n));
	if length(arg) == size(S,1)
	  xlabel = arg;
	else
	  error('The argument to ''XLabel'' has the wrong size.'); 
	end
      elseif strcmp(arg, 'ylabel')
	n = n + 1;
	eval(sprintf('arg = arg%d;', n));
	if length(arg) == size(S,2)
	  ylabel = arg;
	else
	  error('The argument to ''YLabel'' has the wrong size.'); 
	end
      elseif strcmp(arg, 'colormap')
	n = n + 1;
	eval(sprintf('arg = arg%d;', n));
	if size(arg,2) == 3
	  colmap = arg;
	else
	  error('The argument to ''Colormap'' has a wrong size.'); 
	end
      elseif strcmp(arg, 'scale')
	n = n + 1;
	eval(sprintf('arg = lower(arg%d);', n));
	if strcmp(arg, 'linear')
	  scale = 1;
	elseif strcmp(arg, 'sqrt')
	  scale = 2;
	else
	  error('The argument to ''Scale'' is wrong.'); 
	end
      elseif strcmp(arg, 'contour')
	n = n + 1;
	eval(sprintf('arg = arg%d;', n));
	if all(size(arg) == size(S))
	  Contour = arg;
	else
	  error('The argument to ''Contour'' is wrong.'); 
	end
      elseif strcmp(arg, 'back')
	n = n + 1;
	eval(sprintf('arg = arg%d;', n));
	if all(size(arg) == size(S))
	  Back = arg;
	else
	  error('The argument to ''Back'' is wrong.'); 
	end
      elseif strcmp(arg, 'backtype')
	n = n + 1;
	eval(sprintf('arg = lower(arg%d);', n));
	if strcmp(arg, 'none')
	  backType = 0;
	elseif strcmp(arg, 'contour')
	  backType = 1;
	elseif strcmp(arg, 'overwrite')
	  backType = 2;
	elseif strcmp(arg, 'both')
	  backType = 3;
	else
	  error('The argument to ''BackType'' is wrong.'); 
	end
      elseif strcmp(arg, 'mask')
	n = n + 1;
	eval(sprintf('arg = arg%d;', n));
	if all(size(arg) == size(S))
	  Mask = arg;
	else
	  error('The argument to ''Mask'' is wrong.'); 
	end
      elseif strcmp(arg, 'masktype')
	n = n + 1;
	eval(sprintf('arg = lower(arg%d);', n));
	if isstr(arg) & ismember(arg, { 'none' '>' '><' '==' '<' })
	  maskType = arg; 
	else
	  error('The argument to ''MaskType'' should be a string, eg, ''>'''); 
	end
      elseif strcmp(arg, 'masklevel')
	n = n + 1;
	eval(sprintf('arg = arg%d;', n));
	if length(arg) == 1
	  maskLevel = arg;
	else
	  error('The argument to ''MaskLevel'' must be scalar.'); 
	end
      elseif strcmp(arg, 'maskleveltype')
	n = n + 1;
	eval(sprintf('arg = lower(arg%d);', n));
	if strcmp(arg, 'fractile')
	  maskLevelType = 1;
	elseif strcmp(arg, 'absolute')
	  maskLevelType = 2;
	else
	  error('The argument to ''MaskLevelType'' is wrong.'); 
	end
      
      elseif strcmp(arg, 'colorbar')
	n = n + 1;
	eval(sprintf('arg = arg%d;', n));
	if isreal(arg)
	  if arg == 0
	    bColorbar = 0;
	  else
	    bColorbar = 1;
	  end
	else
	  error('The argument to ''Colorbar'' should be a value..'); 
	end

      elseif strcmp(arg, 'range')
	n = n + 1;
	eval(sprintf('arg = arg%d;', n));
	if length(arg) == 2
	  range = arg;
	else
	  error('The argument to ''range'' must be two scalars.'); 
	end
      
      else
	error(sprintf('Invalid property: %s', arg));
      end
      n = n + 1;
    end


    if strcmp(maskType, 'none')
      Mask = ones(size(S));
    
    elseif strcmp(maskType, '>')
      % Larger than maskLevel
      if maskLevelType == 1
	% Fractile
	MaskSort = sort(Mask(:));
	levelIndex = round((length(MaskSort)-1) * maskLevel)+1;
	Mask = MaskSort(levelIndex) < Mask;
     elseif maskLevelType == 2
	% Absolut
	Mask = maskLevel < Mask;
      end
    
    elseif strcmp(maskType, '><')
      % Absolute value should be large than maskLevel
      if maskLevelType == 1
	% Fractile
	MaskSort = sort(abs(Mask(:)));
	levelIndex = round((length(MaskSort)-1) * maskLevel)+1;
	Mask = MaskSort(levelIndex) < abs(Mask);
       elseif maskLevelType == 2
	% Absolut
	Mask = maskLevel < abs(Mask);
      end
      
    elseif strcmp(maskType, '==')
      % Value should be equal to maskLevel
      if maskLevelType == 1
	% Fractile - what should be done here?
	Mask = maskLevel == Mask;
       elseif maskLevelType == 2
	% Absolut
	Mask = maskLevel == Mask;
      end
    
    elseif strcmp(maskType, '<')
      % Larger than maskLevel
      if maskLevelType == 1
	% Fractile
	MaskSort = sort(Mask(:));
	levelIndex = round((length(MaskSort)-1) * maskLevel)+1;
	Mask = MaskSort(levelIndex) < Mask;
      elseif maskLevelType == 2
	% Absolut
	Mask = maskLevel > Mask;
      end

    end

    % If the range is not specified: use the min and max of the slice.
    if isempty(range)
      range = [ min(S(:)) max(S(:)) ];
    end

    % Make sure that there is a difference between minimum and maximum
    % range.
    if ~diff(range)
      range(2) = range(1) * (1 + eps) + realmin;
    end
    
    ha = gca;
    hold off
    if backType == 0 
      % No background
      ver = (version);
      ver = str2num(ver(1:3));
      menuhandle = findobj(get(0,'children'),'tag','TagMenuMosaic');
      if ver >= 5.2 & strcmp(get(menuhandle, 'Checked'), 'on'),
	imagesc(xlabel, ylabel, (S.*Mask)', range);
	colormap(colmap);	
	set(gca,'XTick',[],'YTick',[],'ZTick',[]);
      else
	imagesc(xlabel, ylabel, (S.*Mask)', range);
	colormap(colmap);
      end
      
    elseif backType == 1
      
      % Contour background (or rather foreground)
      ver = (version);
      ver = str2num(ver(1:3));
      menuhandle = findobj(get(0,'children'),'tag','TagMenuMosaic');
      if ver >= 5.2 & strcmp(get(menuhandle, 'Checked'), 'on'),
	h = imagesc(xlabel, ylabel, (S.*Mask)', range);
	set(gca,'XTick',[],'YTick',[],'ZTick',[]);
      else
	h = imagesc(xlabel, ylabel, (S.*Mask)', range);
      end

      set(h, 'EraseMode', 'none');
      if min(size(Contour)) > 1
	hold on
	contour(xlabel, ylabel, Contour', 'linespec', 'm-');
	hold off
      end
      colormap(colmap);
      
    elseif backType == 2
      
      % Merged images (i.e. Original and background)
      cmFore = colmap;
      % Should we only use half of the colormap?
      lcm = length(cmFore);
      % cm = cm(1:2:lcm,:);
      cmBack = gray(lcm);
      cmMerge = [cmBack ; cmFore];
      
      Fore = S.*Mask;

      % Scale to min and max of current slice
      %minFore = min(Fore(:));
      %maxFore = max(Fore(:));
      % Scale to max and min of current volume
      minFore = range(1);
      maxFore = range(2);

      minBack = min(Back(:));
      maxBack = max(Back(:));
      imageMerge = round((lcm-1) * (Back-minBack) / ...
	  (maxBack-minBack)) + 1;
      imageFore = round((lcm-1) * (Fore-minFore) / (maxFore-minFore+realmin) ...
	  + lcm + 1);

      indices = find(Mask(:));
      imageMerge(indices) = imageFore(indices);
      image(xlabel, ylabel, imageMerge');
      
      cmValues = (minFore:(maxFore-minFore)/(lcm-1):maxFore)';
      colormap(cmMerge);

      ver = (version);
      ver = str2num(ver(1:3));
      menuhandle = findobj(get(0,'children'),'tag','TagMenuMosaic');
      if ver >= 5.2 & strcmp(get(menuhandle, 'Checked'), 'on'),
	set(gca,'XTick',[],'YTick',[],'ZTick',[]);
      else
      end
      
      
    % Add extra routine to plot BOTH contour and background
    elseif backType == 3
      % Merged images
      cmFore = colmap;
      % Should we only use half of the colormap?
      lcm = length(cmFore);
      % cm = cm(1:2:lcm,:);
      cmBack = gray(lcm);
      cmMerge = [cmBack ; cmFore];
      
      Fore = S.*Mask;

      % Scale to min and max of current slice
      %minFore = min(Fore(:));
      %maxFore = max(Fore(:));
      % Scale to max and min of current volume
      minFore = range(1);
      maxFore = range(2);
      
      minBack = min(Back(:));
      maxBack = max(Back(:));
      
      imageMerge = round((lcm-1) * (Back-minBack) / ...
	  (maxBack-minBack)) + 1;
      imageFore = round((lcm-1) * (Fore-minFore) / (maxFore-minFore+realmin) ...
	  + lcm + 1);

      indices = find(Mask(:));
      imageMerge(indices) = imageFore(indices);
      h = image(xlabel, ylabel, imageMerge');
      
      cmValues = (minFore:(maxFore-minFore)/(lcm-1):maxFore)';


      % Add in code from contour routine...

      % Contour background (or rather foreground)
      set(h, 'EraseMode', 'none');
      if min(size(Contour)) > 1
	hold on
	contour(xlabel, ylabel, Contour', 'linespec', 'm-');
	hold off
      end
%      colormap(colmap);
      colormap(cmMerge);
        
      ver = (version);
      ver = str2num(ver(1:3));
      menuhandle = findobj(get(0,'children'),'tag','TagMenuMosaic');
      if ver >= 5.2 & strcmp(get(menuhandle, 'Checked'), 'on'),
	set(gca,'XTick',[],'YTick',[],'ZTick',[]);
      else
      end
            
    else
      error('Ops, wrong backType')
    end

%      imageMin = min(min(arg1));
%      imageMax = max(max(arg1));
%      if imageMin == imageMax
%	imagesc(arg1',[ imageMin imageMax+1]);
%      else
%	imagesc(arg1',[ imageMin imageMax]);
%      end
    
    set(gca, 'YDir', 'normal');
    if bColorbar

      axes(ha);   
      hcb = colorbar;
      % Set 'Tag' property to allow easier retrieval for repositioning etc
      set(hcb, 'Tag', 'colorbar'); 
      if any(backType == [2 3])
	% Yes, Hacking
	hcbImage = findobj(hcb, 'type', 'image');
	set(hcbImage,  'CData', (lcm+1:(2*lcm))');
	ver = sscanf(version, '%f'); 
	if ver(1) >= 5.0
	  oldTick = get(hcb, 'YTickLabel');
	else
	  oldTick = get(hcb, 'YTickLabels');
	end
	if isempty(cmValues)
	  % No voxels mask through
	  newTick = zeros(size(oldTick,1),1);
	else
	  for t = 1:length(oldTick)
	    newTick(t,:) = cmValues(str2num(oldTick(t,:))/2);
	  end
	end
	newTick = num2str(newTick, 3);
	if ver(1) >= 5.0
	  set(hcb, 'YTickLabel', newTick);
	else
	  set(hcb, 'YTickLabels', newTick);
	end
      end
      
      axes(ha);   
      drawnow
    end          

    hold on














