% FUNCTION TIMESEG = REMOVE_SIL_FROM_TIMESEG( IN_TIMESEG, SIL_MIN_DUR_SEC )  
%
% IN_TIMESEG and TIMESEG are structures such as returned by READ_TIMESEG.
%
% SIL_MIN_DUR_SEC is a scalar, the minimum duration to apply on silence (seconds).
%
% See also:  READ_TIMESEG
%
% By G.LATHOUD at IDIAP
% lathoud@idiap.ch

function timeseg = remove_sil_from_timeseg( in_timeseg, sil_min_dur_sec )  

  if nargin < 2
    error( 'remove_sil_from_timeseg needs 2 input arguments' );
  end
  
  timeseg = in_timeseg;

  % First merge any two consecutive segments with same label
  
  for a = 1:timeseg.nChannels
    seg = timeseg.seg{a};
    ind = sort( find( ~diff( seg( 3, : ) ) ) );

    for b = fliplr( ind )
      tmp = [ seg( 1, b ); seg( 2, b+1 ); seg( 3, b ) ];
      seg = [ seg( :, 1:b-1 )  tmp  seg( :, b+2:end ) ];
    end
    
    timeseg.seg{a} = seg;
    
  end
  
  % Second remove all silent segment smaller than "sil_min_dur_sec"
  
  for a = 1:timeseg.nChannels
    
    timeseg.seg{ a } = remove_sil_from_seg( timeseg.seg{a}, sil_min_dur_sec );
    
  end
  
