%function livedisplay(refres,timel,senso,fs)
% LIVEDISPLAY(refres,timel,senso,fs)
%
% Makes a live display of an iOS sensor
%
% INPUT
%
% refres     Seconds to refresh top window [default: 3]
% timel      Seconds to show in bottom window [default: 60]
% senso      Which sensor, {'acc', 'ang'} 
% fss        Sampling rate string [default: 10 Hz is 'medium']
%
% Last modified by fjsimons-at-alum.mit.edu, 05/14/2016

% Enable the device
byhand=0;
if byhand==1
   % Make sure you have the bridge
   connector on
   % Activates the mobile device
   clear m
   m=mobiledev;
end

% Set parameters
refres=5;
timel=60;
senso='ang';
senso='acc';
fss='medium';

% Sampling frequency (Hz)
m.SampleRate=fss;
switch fss
  case 'medium'
    fs=10;
end	

% Figure out what to set
switch senso
   case 'acc'
      s='AccelerationSensorEnabled';
      f='accellog';
      yls='acceleration';
      unx='m/s^2';
      lgs={'a_X','a_Y','a_Z'};
   case 'ang'
      s='AngularVelocitySensorEnabled';
      f='angvellog';
      yls='angular velocity';
      unx='rad/s';
      lgs={'\omega_X','\omega_y','\omega_z'};
end

% Construct the display
figure(1)
clf	  
ah(1)=subplot(211);
ah(2)=subplot(212);

% Now make a running display out of this

% Turns or keep on the sensor in question
m.(s)=1;
% Start or continue collecting the data
m.Logging=1;

while 1
  % Load what you have on the sensor
  [a,t]=feval(f,m);

  % Restrict to longest that you will be showing
  try
    a=a(end-fs*timel:end,:);
    t=t(end-fs*timel:end,:);
  end  

  % Demean the segment under consideration
  am=mean(a); 
  da=a-repmat(am,size(a,1),1);

  % Plot individual channels
  axes(ah(1)) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  dm=mean(rms(da));
  ch1=da(:,1)+dm;
  ch2=da(:,2);
  ch3=da(:,3)-dm;

  p(1)=plot(t,ch1,'b'); hold on
  p(2)=plot(t,ch2,'r'); 
  p(3)=plot(t,ch3,'g'); hold off

  leg(1)=legend(lgs,'Location','NorthWest');
  yl(1)=ylabel(sprintf('%s (demeaned)',yls));
  xl(1)=xlabel('time');

  % Plot magnitudes
  axes(ah(2)) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  p(4)=plot(t,rms(a'),'k'); grid on
  yl(2)=ylabel(sprintf('%s (magnitude)',yls));
  xl(2)=xlabel('time');

  % Embellish
  longticks(ah,2)
  set(ah,'xgrid','on','ygrid','on')
  %  set(ah(1),'ylim',[-dm dm])
  set(ah(1),'xlim',t(end)-[refres 0])
  set(ah(2),'xlim',t(end)-[timel 0])
  set(p(1:3),'LineW',2)
  set(p(4),'LineW',2)
  set([xl yl ah],'FontS',15)
  % Increment
  pause(refres)
end



