% FUNCTION PLOT_MULTI_CLUSTER( T, X, TAG, [ SELECTED_TAG_LIST ] )

function plot_multi_cluster( t, x, tag, selected_tag_list )

  SMALL_CLUSTER = 2;
  
  if nargin < 3
    error( 'plot_cluster needs at least 3 parameters.' );
  end
  
  tag_list = unique( tag( find( ~isnan( tag ) ) ) );

  if ~exist( 'selected_tag_list', 'var' )
    selected_tag_list = [];
  end
  
  n_frames = length( x );
  
  not_selected_tag_list = setdiff( tag_list, selected_tag_list );
  
  if ~exist( 'color', 'var' )
    color = 'b.-';
  end
  
  hold on;
  color_list = {'b.-', 'm.-', 'g.-','r.-','c.-' };
  color_last_frame  = repmat( NaN, 1, length( color_list ) );
  i_col = 0;
  
  for a = 1:length( not_selected_tag_list )
    
    tag_frames = find( tag == not_selected_tag_list( a ) );
    if length( tag_frames ) < SMALL_CLUSTER
      a_color = 'k.-';
      color_last_frame( find( color_last_frame < tag_frames( 1 ) ) ) = NaN;
    else
      i_col = 1 + mod( i_col, length( color_list ) );
      old_i_col = i_col;
      while ~isnan( color_last_frame( i_col ) )
	i_col = 1 + mod( i_col, length( color_list ) );

	% Avoid deadlock while looping through colors
	if i_col == old_i_col 
%	  disp( 'deadlock' );
	  [ tmp, i_col ] = min( color_last_frame );
	  color_last_frame( i_col ) = NaN;
	end
      
      end
      color_last_frame( i_col ) = tag_frames( end );
      color_last_frame( find( color_last_frame < tag_frames( 1 ) ) ) = NaN;
      
      a_color = color_list{ i_col };
    end
    
    plot( t( tag_frames ), x( tag_frames ), a_color );

  end
  
  for a = 1:length( selected_tag_list )
    tag_frames = find( tag == selected_tag_list( a ) );
    plot( t( tag_frames ), x( tag_frames ), 'ro' );
  end
  
  hold off
  