dur=6.2;     %duratin of signal seconds
frq=1;       %frequency - Hz
del=0.01;    %time step -dt

%ffsets and amplitude of the three signals, Offsets in seconds
off1= 0.0;  
off2= 0.1;
off3= 0.2; 
amp1=1.;
amp2 =0.9;
amp3 = 0.75;

t = [0:del:dur]; % vector of time values

%triangle wave
%{
d = 0 :2  : dur;           % 1 repetition freq 
x1 = amp1*(pulstran(t+off1,d,'tripuls',2,0));
x2 = amp2*(pulstran(t+off2,d,'tripuls',2,0));
x3 = amp3*(pulstran(t+off3,d,'tripuls',2,0));
plot(t,x1,'Color','g','LineWidth',2);hold on;
plot(t,x2,'Color','c','LineWidth',2);
plot(t,x3,'Color','m','LineWidth',2);hold off;

%}

%sin wave
tpf = 2*pi*frq;
u=(t+off1)*tpf;
v=(t+off2)*tpf;
w=(t+off3)*tpf;
x1 = amp1*(sin(u));
x2 = amp2*(sin(v));
x3 = amp3*(sin(w));


b1 = ones(size(t));
b2 = ones(size(t));
b3 = ones(size(t));

% Fail a signal half-way through:
half = round(length(b3)/2);
%b1(half:length(b1))=zeros(1,length(b1)-half+1);
%b2(half:length(b2))=zeros(1,length(b2)-half+1);
b3(half:length(b3))=zeros(1,length(b3)-half+1);

% Initialize output
x = zeros(size(t));
mvs_all_in = zeros(size(t));
mvs_ommission = zeros(size(t));

for i=1:length(t)
% Set previous state
  if i==1,
    xp=0;
  else
    xp=mvs_ommission(i-1);
  end

  if b1(i) 
    y1=x1(i);
  elseif (b2(i) & ~b3(i))
    y1=x2(i);
  elseif (b3(i) & ~b2(i))
    y1=x3(i)
  else 
    y1=xp;
  end

  if b2(i)
    y2=x2(i); 
  elseif (b1(i) & ~b3(i))
    y2=x1(i);
  elseif (b3(i) & ~b1(i))
    y2=x3(i);
  else
    y2=xp; 
  end

  if b3(i)
    y3=x3(i);
  elseif (b1(i) & ~b2(i))
    y3=x1(i);
  elseif (b2(i) & ~b1(i))
    y3=x2(i);
  else
    y3=xp;
  end

  mvs_ommission(i) = midval(y1,y2,y3);
  mvs_all_in(i) = midval(x1(i),x2(i),x3(i));

  end

% Plot out results
% original signals
 figure;  hold all;
 xlabel('Time');
 ylabel('Command');
 plot(t,x1.*b1,'Color','g','LineWidth',2);
 plot(t,x2.*b2,'Color','c','LineWidth',2);
 plot(t,x3.*b3,'Color','m','LineWidth',2);
 
 %plot mid-value select for three signals in
 figure;  hold all;
 title('Mid-Value Select All In');
 xlabel('Time');
 ylabel('Command');
 plot(t,x1,'Color','g','LineWidth',1);
 plot(t,x2,'Color','c','LineWidth',1);
 plot(t,x3,'Color','m','LineWidth',1);
 plot(t,mvs_all_in,'Color','b','LineWidth',4); hold all;
 
 %plot mid-value select for two signals 
 figure;  hold all;
 title('Mid-Ommission');
 xlabel('Time');
 ylabel('Command');
 plot(t,x1.*b1,'Color','g','LineWidth',1);
 plot(t,x2.*b2,'Color','c','LineWidth',1);
 plot(t,x3.*b3,'Color','m','LineWidth',1);
 plot(t,mvs_ommission,'Color','b','LineWidth',4); hold all;
 
 %  plot force fight
 figure;hold all;
 title('Mid-Value Select - Force Fight');
 xlabel('Time');
 ylabel('Command');
 plot(t,mvs_all_in-mvs_ommission,'Color','b','LineWidth',2);

 
 