function sound = urbiGetSound(con,duration, deviceName)
% Record sound from the server (default device : micro.val)
% This function records 'duration' ms of sound from the Urbi
% server (default device : micro.val),
%
% The result is a Sound struct:
%   sound.samples   : vector of samples
%   sound.Fs        : sampling frequency used by the server
%   sound.channel   : number of channels used by the server
%   sound.nbits     : number of bits used by the server
%   sound.length    : number of samples in the sound
%   sound.duration  : duration in ms
%
% use urbiSound2Wav(snd,wavefile) to save sound in wav file format

if (nargin==2)
    deviceName='micro.val';
end

if (nargin <2)
    error(['urbiGetSound(con,duration, deviceName)\n' ...
          '  con : Id of the Urbi server connection\n' ...
          '  duration : duration of sound to record\n' ... 
          '  deviceName : name of the recording device (default : micro.val)'],1);
end


% Get the sound informations
soundUnit = urbiGetVariable(con,deviceName);
nb_to_get = floor(duration / (soundUnit.duration));


% command to get the right number of sound samples
ref_tag = 'gsnd_tag';
urbiClearConnection(con,0);
urbiSend(con, [ 'for(i=0;i<' num2str(nb_to_get) ';i++) gsnd_tag' con.tagOperator  deviceName ';' ]);

% Reception of the samples
length = 0;
samples = [];

for i=1:(nb_to_get)
% checking header
answer=struct('tag','');
while ~strcmp (answer.tag, ref_tag)
    answer=urbiGet(con);
end;


% Data stream length is in bytes
length =  length + answer.value.length;

% getting samples
samples = [samples answer.value.samples ];

end;

% duration
duration = length/(soundUnit.Fs*soundUnit.channel*(soundUnit.nbits/8))*1000;


% constructing output
sound = struct('samples',samples,'Fs',soundUnit.Fs,'nbits', soundUnit.nbits,...
    'length', length, 'channel', soundUnit.channel, 'duration', duration);


