% TWIDOMFR.M
% This file calculates the dominant frequency of twiddling. The input
% parameters are the vertical co-ordinates of forearm markers as a
% function of time. They can be the output parameters of sorttwi.m,
% ry and ly for the right and left forearms.
% The output parameter is the average frequency for both hands and
% the related standard deviation.
%
for i=1:2,
  if i == 1,
   y = ly;
  else
   y = ry;
  end
  j=1;
  k=1;

% The recordings started when the persons were not moving their forearms.
% The following 'while' cycle searches for the beginning of the twiddling movement.

  while ((y(j)<y(1)+100) & (y(j)>y(1)-100))
    j=j+1;
  end

% The following 'while' cycle searches for maximum values with a 200 ms window.

  while (j<800)
    if (y(j) == max(y(max(1,j-10):min(800,j+10)))),
      localmaxind(k)=j;
      k=k+1;
      j=j+9;
    end
    j=j+1;
  end
t=6
% The following 'for' cycle searches for the minimum values between the adjacent
% maximum values.

  for j=2:length(localmaxind),
    [dummy, localminind(j-1)]=min(y(localmaxind(j-1):localmaxind(j)));
    localminind(j-1)=localminind(j-1)+localmaxind(j-1);
  end
  if i == 1,
    leftlocalminind=localminind;
    leftlocalmaxind=localmaxind;
    clear localminind localmaxind
  else
    rightlocalminind=localminind;
    rightlocalmaxind=localmaxind;
  end
end

for i=1:length(leftlocalmaxind)-1;
    periodlmax(i)=leftlocalmaxind(i+1)-leftlocalmaxind(i);
end
for i=1:length(leftlocalminind)-1;
    periodlmin(i)=leftlocalmaxind(i+1)-leftlocalmaxind(i);
end
for i=1:length(rightlocalmaxind)-1;
    periodrmax(i)=rightlocalmaxind(i+1)-rightlocalmaxind(i);
end
for i=1:length(rightlocalminind)-1;
    periodrmin(i)=rightlocalmaxind(i+1)-rightlocalmaxind(i);
end

% Determination of the amplitudes

for i=1:min(length(leftlocalminind), length(leftlocalmaxind)),
    leftampl(i)=ly(leftlocalmaxind(i))-ly(leftlocalminind(i));
end

for i=1:min(length(rightlocalminind), length(rightlocalmaxind)),
    rightampl(i)=ry(rightlocalmaxind(i))-ry(rightlocalminind(i));
end
