function seg = extract_subset_from_seg( in_seg, in_subset, small_time )

% Check input parameters
  
  if nargin < 2
    error( 'extract_subset_from_seg: needs at least 2 input arguments' );
  end
  
  if nargout < 1
    error( 'extract_subset_from_seg: needs one output argument' );
  end
  
  if ~exist( 'small_time', 'var' )
    small_time = 1e-10;
  end
  
  seg = [];
  
  if ~isempty( in_seg )
    if size( in_seg, 1 ) ~= 3
      error( 'extract_subset_from_seg: "in_seg" input parameter must be a matrix with 3 rows !' );
    end
  else
    if ~strcmp( warning, 'off' )
      disp( 'extract_subset_from_seg: WARNING! Empty input parameter "in_seg".' );      
    end
    seg = [];
    return;
  end

  if ~isempty( in_subset )
    if size( in_subset, 1 ) ~= 2
      error( 'extract_subset_from_seg: "in_subset" input parameter must be a matrix with 2 rows !' );
    end
  else
    if ~strcmp( warning, 'off' )
      disp( 'extract_subset_from_seg: WARNING! Empty input parameter "in_subset".' );
    end
    seg = [];
    return;
  end
  
  %%%
  
  % Now we can extract from the activity/silence segmentation "in_seg"
  % the subset defined by "in_subset"
  
  % ( 1 ) Build an oversegmentation

  t = [];
  t = [ t in_seg(1,:) in_seg(2,:) ];
  t = [ t in_subset(1,:) in_subset(2,:) ];
  
  t = sort( unique( t ) );
  
  % "unique" is not enough to suppress duplicates
  % minor errors may appear (e.g. 1e-14)
  t = t( find( diff( [ -Inf t ] ) > small_time ) );
  
  if length( t ) < 2
    seg = [];
    return;
  end
  
  seg = [ t(1:end-1); t(2:end) ];
  
  % ( 2 ) Keep only segments in "in_subset"
  
  seg_middle = mean( seg( 1:2, : ), 1 );
  nseg = length( seg_middle );
  
  for a = nseg:-1:1
    
    t = seg_middle( a );
    
    if ~any( ( in_subset(1,:) <= t ) & ( t <= in_subset(2,:) ) )

      % This segment is not in "in_subset", remove it
      seg = [ seg( :, 1:a-1 )   seg( :, a+1:end ) ];
    end
  end
  
  
  % ( 3 ) Find activity for each segment
  % -> copy activity indicator from "in_seg( 3,: )"

  seg( 3,: ) = 0;
  
  seg_middle = mean( seg( 1:2, : ), 1 );
  nseg = length( seg_middle );
  
  for a = 1:nseg
  
    t = seg_middle( a );

    seg( 3, a ) = any( (in_seg(1,:) <= t) & (t <= in_seg(2,:)) & in_seg( 3,: ) );
    
  end
  
  % ( 4 ) Merge consecutive segments with same activity tag
  
  for a = nseg-1:-1:1

    if ( seg( 3, a ) == seg( 3, a+1 )  ) & ( abs( seg( 2, a ) - seg( 1, a+1 ) ) < small_time )
      tmp = [ seg( 1,a ); seg( 2:3,a+1 ) ];
      seg = [ seg( :, 1:a-1), tmp, seg( :, a+2:end ) ];
    end
    
  end
  