function scope3(varargin)
% display of an incoming analog input signal.
% Hacked by BRL from the Mathworks FFT demo program. 
% ===20 July 2000===
%
%    scope1 creates an analog input object associated with the 
%    winsound adaptor with device identification 0.  The incoming 
%    signal of the created analog input object is plotted.
%
%    Examples:
%      scope1
%      

global hFig

%figure out number of arguments
%need to do this because DAQ events like to insert parameters in 
%callbacks
if (nargin == 0)
   fcn = 'makeGUI';
elseif (nargin == 3 & varargin{3}=='freeDisp')  %timer event
   fcn='freeDisp';
elseif (nargin == 3 & varargin{3}=='timeout')  %no trigger event
   fcn='freerun';   
else
   fcn=varargin{1};
end

% Based on function, call the appropriate 
% local function.
switch fcn
   
case 'makeGUI'
   % Create the analog input object.
   data = localInitAI;
   % Create the  figure.
   data = localInitFig(data);
   hFig = data.handle.figure; %figure handle for data storage later
   
case 'close' 
   data=get(hFig,'UserData');
   localClose(data);
   return;  %Don't want to try to store data in non-existent handles
   
case 'single'
   data=get(hFig,'UserData');  
   data = localSingle(data);
   
case 'freerun'
   data=get(hFig,'UserData');  
   data = localFreerun(data);
   
case 'trigger'
   data=get(hFig,'UserData');
   data=localTrigger(data);
   
case 'freeDisp'
   data=get(hFig,'UserData');  
   localFreeDisp(data);
   %return; %no new data to store   
   
case 'setVolts'
   data=get(hFig,'UserData');
   data=localSetVolts(data);   
    
case 'setTime'
   data=get(hFig,'UserData');
   data=localSetTime(data); 
   
end %switch fcn

% Update the figure's UserData to store program state
set(hFig,'UserData',data);

% ***********************************************************************   
% Create the object and get the data
function data = localInitAI

% Initialize variables.
data = [];

adaptor = 'winsound';
id = 0;
chan = 1;

% Object Configuration.
% Create an analog input object with one channel.
ai = analoginput(adaptor, id);
ch = addchannel(ai, chan);

% Configure the analog input object.
set(ai, 'SampleRate', 44100);

% Configure the analog input object to trigger manually.
set(ai, 'SamplesPerTrigger', 4410);
set(ai, 'TriggerRepeat', 1);
set(ai, 'TriggerType', 'Manual');

% Initialize callback parameters.  The TimerAction is initialized 
% after figure has been created.
set(ai, 'TimerPeriod', 0.2);  

%get(ai,'timeraction')
% Object Execution.
% Start the analog input object.
start(ai);
trigger(ai);

% Obtain the available time and data.
[d,time] = getdata(ai, ai.SamplesPerTrigger);

% Update the data structure.
data.ai = ai;
data.getdata = [d time];
data.handle = [];
data.ch = ch;

% ***********************************************************************   
% Create the display.
function data = localInitFig(data)

% Initialize variables.
btnColor=get(0,'DefaultUIControlBackgroundColor');

% Position the GUI in the middle of the screen
screenUnits=get(0,'Units');
set(0,'Units','pixels');
screenSize=get(0,'ScreenSize');
set(0,'Units',screenUnits);
figWidth=600;
figHeight=300;
figPos=[(screenSize(3)-figWidth)/2 (screenSize(4)-figHeight)/2  ...
      figWidth                    figHeight];

% Create the figure window.
hFig=figure(...                    
   'Color'             ,btnColor                 ,...
   'IntegerHandle'     ,'off'                    ,...
   'DoubleBuffer'      ,'on'                     ,...
   'DeleteFcn'         ,'scope3(''close'')',...
   'MenuBar'           ,'none'                   ,...
   'HandleVisibility'  ,'on'                     ,...
   'Name'              ,'Winsound one-channel scope'  ,...
   'Tag'               ,'One Channel scope'  ,...
   'NumberTitle'       ,'off'                    ,...
   'Units'             ,'pixels'                 ,...
   'Position'          ,figPos                   ,...
   'UserData'          ,[]                       ,...
   'Colormap'          ,[]                       ,...
   'Pointer'           ,'arrow'                  ,...
   'Visible'           ,'off'                     ...
   );

% Create Data subplot.
hAxes(1) = axes(...
   'Units'             ,'normalized', ...
   'Position'          , [0.08 0.1 0.5 .85],...
   'fontsize'          ,8, ...
   'Parent'            , hFig,...
   'XLim'              , [0 get(data.ai, 'SamplesPerTrigger')],...
   'YLim'              , [-0.5 0.5]...
   );

% Plot the data.
hLine(1) = plot(data.getdata(:,1),'w');
set(hAxes(1), 'XLim', [0 get(data.ai,'SamplesPerTrigger')/44100]);
set(hAxes(1), 'YLim', [-1 1]);

set(hAxes(1), 'color', [.1 .4 .2]);
grid on

% Label the plot.
xlabel('Time (sec)');
ylabel('Winsound.0 (Volts)');
%title('Analog Data Acquisition');

%Frames==================================
%frame for trigger stuff
uicontrol( ...
   'style', 'frame', ...
   'Units','normalized', ...
   'position', [.86 .1 .13 .9], ...
   'backgroundcolor', [.8,.8,.8] ...
   );

%frame for vertical stuff
uicontrol( ...
   'style', 'frame', ...
   'Units','normalized', ...
   'position', [.6 .1 .13 .9], ...
   'backgroundcolor', [.8,.8,.8] ...
   );

%frame for horizontal stuff
uicontrol( ...
   'style', 'frame', ...
   'Units','normalized', ...
   'position', [.73 .1 .13 .9], ...
   'backgroundcolor', [.8,.8,.8] ...
   );

%Trig controls==================================
% Create trigger radio buttons.
hsingle = uicontrol(...
   'Parent'          , hFig,...
   'Style'           , 'radiobutton',...
   'Units'           , 'normalized',...
   'Position'        , [0.87 0.9 0.1 0.06],...
   'Value'           , 0,...
   'String'          , 'Single',...
   'Callback'        , 'scope3(''single'');');

hfree = uicontrol(...
   'Parent'          , hFig,...
   'Style'           , 'radiobutton',...
   'Units'           , 'normalized',...
   'Position'        , [0.87 0.85 0.1 0.06],...
   'Value'           , 1,...
   'String'          , 'Freerun',...
   'Callback'        , 'scope3(''freerun'');');

%create trigger button
htrig = uicontrol(...
   'Parent'          , hFig,...
   'Style'           , 'pushbutton',...
   'Units'           , 'normalized',...
   'Position'        , [0.87 0.75 0.1 0.06],...
   'Value'           , 1,...
   'enable'          , 'off', ... %disabled in freerun mode
   'String'          , 'Trigger',...
   'Callback'        , 'scope3(''trigger'');');

%Vert controls==================================
hvolt = uicontrol(...
  'style', 'listbox', ...
   'Units','normalized', ...
   'position', [.61 .5 .11 .2], ...
   'string','0.1|0.2|0.5|1.0', ...
   'value', 4, ...  %initially 1.0 fullscale
   'callback', 'scope3(''setVolts'');'...
   );

uicontrol(...
   'style', 'text',...
   'string','V fullscale',...
   'Units','normalized', ...
   'position', [.61 .7 .11 .06]...
   );

%Horizontal controls======================
htime = uicontrol(...
  'style', 'listbox', ...
   'Units','normalized', ...
   'position', [.74 .5 .11 .2], ...
   'string','0.01|0.02|0.05|0.10', ...
   'value', 4, ...  %initially 0.10 fullscale time
   'callback', 'scope3(''setTime'');'...
   );

uicontrol(...
   'style', 'text',...
   'string','Timebase',...
   'Units','normalized', ...
   'position', [.74 .7 .11 .06]...
   );

%Menu==================================
%A close menu item
hmenu(1) = uimenu('Parent', hFig,...
   'Label', 'File');
hmenu(2) = uimenu(hmenu(1),...
   'Label', 'Close',...
   'Callback', 'scope3(''close'',gcbf)');

% Store the handles in the data matrix.
data.handle.figure = hFig;
data.handle.axes = hAxes;
data.handle.line = hLine;
data.handle.single = hsingle;
data.handle.free = hfree;
data.handle.trig = htrig;
data.handle.volt = hvolt;
data.handle.time = htime;

data.state = 0;

% Set the axes handlevisibility to off.
set(hAxes, 'HandleVisibility', 'off');

% Store the data matrix and display figure.
set(hFig,'Visible','on','userdata',data,'HandleVisibility', 'off');

% Configure the callback to update the display.
%Note that the TimerAction property prepends TWO parameters to the
%called function: object and event
%Therefore, the following call to scope3 passes THREE arguments total

set(data.ai, 'TimerAction', {'scope3','freeDisp'});

% ***********************************************************************  
% Close the figure window.
function localClose(data)

% Stop the device if it is running and delete the object.
if isvalid(data.ai)
   if strcmp(get(data.ai, 'Running'), 'On')
      stop(data.ai);
   end
   delete(data.ai);
end

% Close the figure window.
delete(data.handle.figure);

% ***********************************************************************  
% Single trace capture
function data = localSingle(data)

%radio button exclusion
set(data.handle.free, 'Value', 0); 

%enable trigger button
set(data.handle.trig, 'enable', 'on');  

% Stop the device.
stop(data.ai);
%Turn off auto refresh
set(data.ai, 'TimerAction', '');

%trigger > software (voltage level on ch 0)
set(data.ai, 'TriggerChannel', data.ch);
set(data.ai, 'TriggerType', 'Software');
set(data.ai, 'TriggerCondition', 'rising');
set(data.ai, 'TriggerConditionValue', 0.2);
set(data.ai, 'TriggerRepeat', 0);  

set(data.ai, 'Timeout', 2);
set(data.ai, 'RuntimeErrorAction',{'scope3','timeout'})

% Store the new state (timer off).
data.state = 1;

% ***********************************
% Continuous data collection
function data = localFreerun(data)

%radio button exclusion
set(data.handle.single, 'Value', 0);  

%disable trigger button
set(data.handle.trig, 'enable', 'off');  

%trigger > manual (trigger on call)
set(data.ai, 'TriggerType', 'manual');
set(data.ai, 'TriggerRepeat', 1);

% Store the new state (timer on).
data.state = 0;

%Turn on auto refresh
set(data.ai, 'TimerAction', {'scope3','freeDisp'});
set(data.ai, 'RuntimeErrorAction','')

% Start the device.
start(data.ai);
trigger(data.ai);



%***************************************
function data = localSetVolts(data)

hAxes=data.handle.axes;

switch get(data.handle.volt, 'value');
   
case 1
   set(hAxes(1), 'YLim', [-.1 .1]);
case 2
   set(hAxes(1), 'YLim', [-.2 .2]);
case 3
   set(hAxes(1), 'YLim', [-.5 .5]);
case 4
   set(hAxes(1), 'YLim', [-1 1]);
end

%***************************************
function data = localSetTime(data)

hAxes=data.handle.axes;
obj=data.ai;

%stop analog input if it is running, so 
%the number of samples can be changed
if data.state==0
   stop(obj)
end

switch get(data.handle.time, 'value');
   
case 1
   set(hAxes(1), 'XLim', [0 .01]);
   set(obj, 'SamplesPerTrigger', 441);
case 2
   set(hAxes(1), 'XLim', [0 .02]);
   set(obj, 'SamplesPerTrigger', 882);
case 3
   set(hAxes(1), 'XLim', [0 .05]);
   set(obj, 'SamplesPerTrigger', 2205);
case 4
   set(hAxes(1), 'XLim', [0 .1]);
   set(obj, 'SamplesPerTrigger', 4410);
end

%restart it if it was running
if data.state==0
   start(obj)
   trigger(obj);
   y = getdata(obj, obj.SamplesPerTrigger);  
end

% ***********************************************************************
%Maunally trigger the event with a button click
function data = localTrigger(data)

% Get the handles.
obj = data.ai;
hAxes = data.handle.axes;
hLine = data.handle.line;

% Get one trace
start(obj);
%trigger(obj);
%while strcmp(obj.Running, 'On')
%end

y=[];
x = linspace(0, get(obj,'SamplesPerTrigger')/44100, get(obj,'SamplesPerTrigger'));
%make sure we actually got all the data
while length(y) ~= length(x)
   y = getdata(obj, obj.SamplesPerTrigger); 
end

stop(obj);

% Update the plot.
set(hLine(1), 'YData', y, 'XData', x);

drawnow;

% ***********************************************************************  
% Update the plot.
function localFreeDisp(data)

% Get the handles.
obj = data.ai;

hAxes = data.handle.axes;
hLine = data.handle.line;

% Execute a peekdata and make sure we got the right amount of data
y=[];
x = linspace(0, get(obj,'SamplesPerTrigger')/44100, get(obj,'SamplesPerTrigger'));

%make sure we actually got all the data
while length(y) ~= length(x)
   y = peekdata(obj, obj.SamplesPerTrigger); 
end

% Update the plot.
set(hLine(1), 'YData', y, 'XData', x);

drawnow;

% ***********************************************************************