function file = sound_save(lib,sound,state,opt)

% sound_save - save sound structure to file in library
% ----------------------------------------------------
%
% file = sound_save(lib,sound,state,opt)
%
% Input:
% ------
%  lib - library to save sound to (def: active library)
%  sound - sound to save
%  state - browser state to save
%  opt - refresh option
%
% Output:
% -------
%  file - file saved

%--------------------------------
% Author: Harold Figueroa
%--------------------------------
% $Revision: 4319 $
% $Date: 2006-03-20 18:06:08 -0500 (Mon, 20 Mar 2006) $
%--------------------------------

%-----------------------------------
% HANDLE INPUT
%-----------------------------------

%--
% set default refresh
%--

if ((nargin < 4) || isempty(opt))
	opt = 1;
end 

%--
% set default empty state
%--

if (nargin < 3)
	state = [];
end

%--
% check that sound is in library
%--

file = get_library_sound_file(lib,sound_name(sound));

% NOTE: check for the sound root directory

[par,leaf,ignore] = fileparts(file);

if (~exist_dir(par))
	error(['Root directory for ''', leaf, ''' not found in library.']);
end

%-------------------------------------------
% SAVE SOUND AND STATE
%-------------------------------------------
	
try
	save(file,'sound','state');
catch
	xml_disp(lasterror);
end

%--
% update library cache if needed
%--

% NOTE: this might seem extraneous, but we are storing in a library, not just a file

if (opt)
	get_library_sounds(lib,'refresh');
end
