% FUNCTION TIMESEG = READ_TIMESEG( FILENAME )
%
% Version 1 - 030910
% lathoud@idiap.ch
%
% To build a TIMESEG object that define concurrent speaker segments
% (i.e. each speaker is segmented separately).
%
%
% Input:
%
% FILENAME (string) points to a file containing a 3-column matrix of
% floats in ASCII format. 
% - each row describes one segment of time.
% - column 1 contains start time of the segment.
% - column 2 contains end time of the segment.
% - column 3 contains 0 (non-speech) or 1 (speech).
% - special rows of "-1 -1 -1" mark the separation between speakers
%
% See "/home/speech/lathoud/tools/matlab/TrainSet-sm01-sns.txt" 
% for an example of a file with 4 speakers.
% 
%
% 
% Output:
%
% TIMESEG: an object defining segmentation of concurrent speakers,
% as read by READ_TIMESEG. Fields are:
% - TIMESEG.nChannels:  an integer defining the number of speakers
% - TIMESEG.startTime:  a float, in seconds, beginning of the segmentation.
% - TIMESEG.endTime:    a float, in seconds, end of the segmentation.
% - TIMESEG.seg:        a list of nChannels matrices. Each matrix defines
% the speech/non-speech segmentation for one speaker: each column is a segment.
%   - row 1 is start of the segment in seconds.
%   - row 2 is end of the segment in seconds.
%   - row 3 is 0 or 1. 0 means non-speech, 1 means speech.
%
% 
% SEE ALSO TIMESEG2FRAMESEG to convert to a segmentation in terms of frames.


function timeseg = read_timeseg( filename )
  
  if nargin < 1
    error( 'timeseg needs one parameter' );
  end
  
  fid = fopen( filename, 'rt' );
  if fid < 0
    error( [ 'timeseg could not read-open ' filename ] );
  end
  m = fscanf( fid, '%f', [3 Inf] );
  fclose( fid );
  
  % Split the matrix into separate channels
  separators = [ 0   find( m(3,:) < 0 )   1+size(m,2) ];
  timeseg.nChannels = length( separators ) - 1;

  channelMat = {};
  for a = 1:timeseg.nChannels
    channelMat{ end+1 } = m( :, separators( a )+1:separators( a+1 )-1 );
  end
  
  % Store global values
  timeseg.startTime = channelMat{ 1 }( 1,1 );
  timeseg.endTime   = channelMat{ 1 }( 2, end );
  
  % Store each matrix
  timeseg.seg = {};
  for a = 1:timeseg.nChannels
    timeseg.seg{ a } = channelMat{ a };
  end
  