function ortho_gest   % code by jph
global N K

K= 7;                 % control points of spline curve
N= 36;                % samples of arc-length reparametrized curve
T= 0.25;              % threshold


if 1                  % add circle as first shape (not mandatory)
  t=linspace(0,2*pi,N);
  c=jinorm([cos(t) sin(t)]);
  Cx=c(  1:N  );
  Cy=c(N+1:end);
else
  Cx=zeros(0,N);
  Cy=zeros(0,N);
end

while 1
  c=jigest;
  cx=c(  1:N  );
  cy=c(N+1:end);  
  if all(abs(Cx*cx')<T')&all(abs(Cy*cy')<T')
    disp(abs([Cx*cx' Cy*cy']))
    figure(2)
    clf reset
    jivis(c)
    drawnow
    a=input('1=reject, 2=keep, 0=exit : ');
    switch a
      case 1,        
      case 2,
        Cx=[Cx;cx];
        Cy=[Cy;cy];
        n=size(Cx,1);
        figure(1)
        clf reset        
        for c1=1:n
          subplot(1,n,c1)
          jivis([Cx(c1,:) Cy(c1,:)])
        end
        save 'curves' Cx Cy
        drawnow
      case 0,        
        return
    end
  end
end


function c=jinorm(c)  % centers curve around origin and normalizes coordinates
global N

px=c(  1:N  );
py=c(N+1:end);
ix=min(min(px)); ax=max(max(px));
iy=min(min(py)); ay=max(max(py));
px=(px-(ix+ax)/2)/(ax-ix);
py=(py-(iy+ay)/2)/(ay-iy);
c=[px py];
c=c/norm(c);


function c=jigest     % generates random gesture
global N K

t=linspace(0,1,100);
P=rand(2,K);
px=interp1(linspace(0,1,K),P(1,:),t,'spline');
py=interp1(linspace(0,1,K),P(2,:),t,'spline');

ix=min(min(px));
ax=max(max(px));
iy=min(min(py));
ay=max(max(py));

px=(px-ix)/(ax-ix);
py=(py-iy)/(ay-iy);

dx=diff(px);
dy=diff(py);
dc=[0 cumsum(sqrt(dx.*dx+dy.*dy))];
dc=dc/dc(end);

dt=linspace(0,1,N);
Ix=interp1(dc,px,dt,'spline');
Iy=interp1(dc,py,dt,'spline');

c=[Ix Iy];
c=jinorm([Ix Iy]);


function jivis(c)     % visualizes gesture
global N

t=linspace(0,1,100);
P1=c(  1:N  );
P2=c(N+1:end);
px=interp1(linspace(0,1,N),P1,t,'spline');
py=interp1(linspace(0,1,N),P2,t,'spline');

plot(px,py); hold on
plot(P1,P2,'r+')
plot(P1(1),P2(1),'go')
axis equal
