function siburec(fs,qua,chn)
% siburec(fs,qua,chn)
% Single Button Audiorecorder Version 1.0
% fs  :  one of the common sample rates 8000, 11025, 
%        22050, and 44100 (in Hz; default: 8000)
% qua :  quantization in Bits
%        must be 8, 16, or 24 on Windows, 8 or 16 on UNIX
%        (default: 16)
% chn :  number of channels must be 1 or 2 (mono or stereo)
%        (default: 1)
% The compiled version of the recorder can be started from 
% the command line by typing
% siburec  (then the default parameters will be taken) or by 
% siburec 11025  or by  siburec 44100 16 2 .
%
% The recorder starts recording by a button push. 
% When the button is pushed again the recording is stopped 
% and is stored as an audio file into the folder "records" 
% in the same directory as the program.  The file name is 
% the concatenation of "rec" and the ISO 8601 string of 
% date and time at the second push. 

% Author:  Klaus von der Heide, e-mail:  dj5hg@qsl.net

% Defaults
% ========
if nargin<1    fs  = 8000;         end  % sample frequency in Hz
if nargin<2    qua = 16;           end  % representation of samples in #bits
if nargin<3    chn = 1;            end  % number of channels
if ischar(fs)   fs = str2num(fs);  end  % if string parameters then convert
if ischar(qua) qua = str2num(qua); end
if ischar(chn) chn = str2num(chn); end

% One-Button Panel
% ================
fh  = figure;
set(fh,'NumberTitle','off','Name','SiBuRec','Units','centimeters','MenuBar','none',...
       'Position',[0.1  5.0  2.8  1.0],'Resize','off','UserData','-')
rec = audiorecorder(fs,16,1);
btn = uicontrol('Style','pushbutton','String','push to record','FontSize',12,...
                'Units','centimeters','Position',[0 0 2.8 1]);
set(btn,'Callback',{@siburecfcn,btn,fh,1,rec})

%-------------------- Callback Function for siburec ----------------------------

function siburecfcn(obj,eventdata,btn,fh,k,rec)
% callback function for onebuttonaudiorecorder
switch k
case 1
   record(rec);
   set(btn,'Callback',{@siburecfcn,btn,fh,2,rec},'String','push to stop','BackgroundColor','r')
case 2
   stop(rec);
   x = getaudiodata(rec,'double');
   x = x/max(abs(x)+0.0002);
   sibp = evalc('which siburec.m');
   ix = findstr('siburec_mcr',sibp);
   if ~isempty(ix)
      pfad = sibp(1:ix(1)-1);
   else
      pfad = sibp(1:findstr(sibp,'siburec.m')-1);
   end
   file = [pfad  'records'  filesep  'rec-'  datestr(now,30)  '.wav']
   while strcmpi(file,get(fh,'UserData'))         % only for very quick clickers
      pause(1.1)          % wait a second not to overwrite the last written file
      file = [pfad(1:findstr(fcn,pfad)-1) 'rec-' datestr(now,30) '.wav'];
   end
   wavwrite(x,get(rec,'SampleRate'),16,file);
   set(fh,'UserData',file)
   set(btn,'Callback',{@siburecfcn,btn,fh,1,rec},'String','push to record','BackgroundColor',0.8*[1 1 1]) 
end
