function StimPlay(varargin)
%plays a wave file

%global fig

% By default make the GUI
%from the command line with no parameters

if (nargin == 0)
    fcn = 'makeGUI';
elseif nargin == 3 & strcmp(varargin{3},'stimaction')  %stim event
    fcn='stimaction';
    fig=findobj('tag','BRLplayback');
else
    fcn=varargin{1};
    fig=findobj('tag','BRLplayback');
end

%This is the main decision point of the function.
%The switch statement is executed once-per-fuction call
switch fcn

    %This code is executed ONCE when the function enters with
    %no arguments
    case 'makeGUI'

        %delete(daqfind);

        %store the name of this executing file
        data.myname = mfilename;

        %feature('javafigures',0);
        %=============================================
        %==Stimulator controls
        %============================================

        % ===Create main figure==========================
        fig = figure('Position',centerfig(800,130),...
            'Resize','off',...
            'NumberTitle','off',...
            'Name','Stimulus Playback',...
            'Interruptible','off',...
            'tag','BRLplayback',...
            'doublebuffer','on',...
            'HandleVisibility','on',...
            'Color',[.7 .7 .7]);

        %===Header text===================================
        uicontrol(gcf,'Style','text', ...
            'String','DAQ Stimulus Playback',...
            'fontsize',14, ...
            'HorizontalAlignment','Center',...
            'Position',[5,100,300,25],...
            'BackgroundColor',[0.8 .8 0.8]);

        % ===The quit button===============================
        uicontrol('Style','pushbutton',...
            'Position',[750 100 45 20],...
            'String','Quit',...
            'Interruptible','off',...
            'BusyAction','cancel',...
            'tag','quitPlayback',...
            'Callback',[data.myname,' quit']);

        %==Mode Chooser=========================
        x=10 ; y=50 ; w=140 ; h=20 ;
        data.mode='Single';
        data.mode1=uicontrol(gcf,'Style','radiobutton', ...
            'String','Single',...
            'Position',[x,y,w,h],...
            'BackgroundColor',[0.8,0.8,0.8], ...
            'tag','modegrp',...
            'value',1,...
            'CallBack',[data.myname,' mode'] );
        data.mode2=uicontrol(gcf,'Style','radiobutton', ...
            'String','Continuous',...
            'Position',[x,y-h,w,h],...
            'BackgroundColor',[0.8,0.8,0.8], ...
            'tag','modegrp',...
            'CallBack',[data.myname,' mode'] );
       
        uicontrol(gcf,'style','text',...
            'Position',[x,y+h,w,h],...
            'BackgroundColor',[0.8,0.8,0.8],...
            'string','Mode');
        data.start=uicontrol(gcf,'Style','Pushbutton', ...
            'String','Start',...
            'Position',[x+80,y-20,60,h],...
            'BackgroundColor',[0.8,0.8,0.8], ...
            'enable','off',...
            'CallBack',[data.myname,' start'] );
        data.trigger=uicontrol(gcf,'Style','Pushbutton', ...
            'String','Play Once',...
            'Position',[x+80,y,60,h],...
            'BackgroundColor',[0.8,0.8,0.8], ...
            'enable','on',...
            'CallBack',[data.myname,' trigger'] );

        %=== input wav file ============================
        data.wavname=uicontrol(...
            'style', 'edit', ...
            'position', [75 5 600 20], ...
            'enable','on',...
            'string',' ');
        
        data.wavnamesel=uicontrol(...
            'style', 'pushbutton', ...
            'position', [0 5 70 20], ...
            'enable','on',...
            'string','WavFile',...
            'callback', [data.myname,' wavfileget']...
            );
        
        %=== set up the analog output ========================================
        daqregister('nidaq');
        [adaptorStrArray, aiParams, CHnames] = daqgate('privateGetAdaptor', 'analogoutput');
        [sel,ok] = listdlg('PromptString','Select an analog output:',...
            'SelectionMode','single',...
            'ListSize', [200 80], ...
            'Name', 'Choose Adaptor', ...
            'ListString',adaptorStrArray);
        if ok %the user actually chose something
            %parse the adaptor info
            adaptorStr = adaptorStrArray{sel};
            index = find(adaptorStr == ' ');
            adaptor = adaptorStr(1:index(1)-1);
            id = adaptorStr(index(1)+1:end);

        else %no choice made
            errordlg('You must choose a adaptor')
            close fig
            return
        end
        %use the adaptor info to build the output object
        data.adaptor = adaptor ; %'nidaq';
        data.id = id ; %'Dev1';
        data.ao = analogoutput(data.adaptor, data.id);
        %data.Fs = get(data.ao,'SampleRate');
        if ~strcmp(lower(adaptor), 'winsound') %nidaq
            data.cho = addchannel(data.ao, 0);
            %data.Fs = 10000; %assumes a fairly fast DAC
            %set(data.ao, 'SampleRate', data.Fs);
        else %winsound
            data.cho = addchannel(data.ao, 1);
            %data.Fs = 44100;
            %set(data.ao, 'SampleRate', data.Fs);
        end
        
        %== Sample rate edit field ========
        x=700 ; y=5 ; w=70 ; h=20 ;
        data.setFs = uicontrol(fig,'Style','text', ...
            'String',' ',...
            'Position',[x,y,w,h],...
            'BackgroundColor',[0.8,0.8,0.8]);
        y=y+h;
        uicontrol(fig,'Style','text', ...
            'String','Sample Rate',...
            'Position',[x,y,w,h],...
            'BackgroundColor',[0.8,0.8,0.8]);

        %put all the variables in a safe place (the figure's data area)
        set(fig,'UserData',data);

        %======================================================
        %UIcontrol callbacks for Playback
        %======================================================
    case 'start'
        data=get(fig,'UserData');
        %determine if starting or stopping
        if strcmp(get(gco,'string'),'Start')
            set(gco,'string','Stop')
            stop(data.ao)
            %set(data.ao,'bufferingconfig',[50000,2])
            putdata(data.ao,[data.wave]);
            set(data.ao,'repeatoutput',inf);
            set(data.ao,'triggertype','manual');
            start(data.ao);
            trigger(data.ao);
        elseif strcmp(get(gco,'string'),'Stop')
            set(gco,'string','Start')
            stop(data.ao);
            set(data.ao,'repeatoutput',0)
        end
        set(fig,'UserData',data);


    case 'wavfileget'
        data=get(fig,'UserData');
        [fname,pname] = uigetfile('*.wav','WAV file');
        if fname~=0
            fullname=strcat(pname,fname)
            [data.wave, data.Fs]=wavread(fullname);
            set(data.wavname,'string',fullname);
            set(data.ao, 'SampleRate', data.Fs);
            set(data.setFs,'string',num2str(data.Fs));
            set(fig,'UserData',data);
        else
            errordlg('You must choose a file')
        end
        
    case 'quit'
        data=get(fig,'UserData');
        close(gcf);
        try
            stop(data.ao)
        end
        delete(data.ao);
        clear data
        %end

    case 'trigger'
        data=get(fig,'UserData');
        stop(data.ao);
        %set(data.ao,'bufferingconfig',[50000,2])
        set(data.ao,'triggertype','manual');
        putdata(data.ao,[data.wave]);
        start(data.ao);
        trigger(data.ao);

    case 'mode'
        data=get(fig,'UserData');
        objhandle=findobj('tag','modegrp');
        clrindex=find(objhandle ~= gco);
        set(objhandle(clrindex),'value',0);
        set(gco,'value',1);
        data.mode=get(gco,'string');
        if strcmp(data.mode,'Continuous')
            set(data.start,'enable','on')
            set(data.trigger,'enable','off')
        elseif strcmp(data.mode,'Single')
            set(data.start,'enable','off')
            set(data.start,'string','Start');
            set(data.trigger,'enable','on')
        end
        set(fig,'UserData',data);

end %of main case statement

%===========================================
%===various subroutines=====================
%============================================================
%===A utility to center the window on the screen============
%===========================================================
function pos = centerfig(width,height)
% Find the screen size in pixels
screen_s = get(0,'ScreenSize');
pos = [screen_s(3)/2 - width/2, screen_s(4)/2 - height/2, width, height];
return


