%Formantmod.m  forms models for the numbers 1 to 5.

warning off
clear Form formant formmod
clf
p=8;
for n=1:5
 for in=1:10
  f=auread(['m',num2str(n),num2str(in-1),'.out']);
  f=filter([1 -15/16],1,f);
  f=f(1:4500); 
  a=find(f>.045);
  f=[f(a(1):4500); zeros(a(1)-1,1)];
  
  l=300;
  for d=1:42
   F=f(1+(d-1)*l/3:(d+2)*l/3);
   F=F.*hamming(l);
   y=ar(F,p);
   [a,b]=th2tf(y);
   Form(:,d)=roots(b);
  end


%---discards poles at 0, pi, and mag<.8
  for i=1:8
   for j=1:42
    if abs(Form(i,j))<.8
     Form(i,j)=NaN;
    end
    if angle(Form(i,j))<.001
     Form(i,j)=NaN;
    end
    if angle(Form(i,j))>3.14
     Form(i,j)=NaN;
    end
   end
  end

%---forms 3X42 matrix with poles ordered
  for j=1:42
   for i=1:3
    [a,b]=min(angle(Form(:,j)));
    formant(i,j)=Form(b,j);
    Form(b,j)=NaN;
   end
  end 
  formant=angle(formant);

%---reorganizes formant frequencies---
reorg=formant;



  for i=1:42
   if reorg(1,i)>1
    reorg(3,i)=reorg(2,i);
    reorg(2,i)=reorg(1,i);
    reorg(1,i)=NaN;
   end
  end
  a=find(reorg(1,:)>.0000001);
  A=reorg(1,a);
  m=mean(A');
  clear a A

  for i=1:42
   if reorg(1,i)>2*m
    reorg(3,i)=reorg(2,i);
    reorg(2,i)=reorg(1,i);
    reorg(1,i)=NaN;
   end

   if reorg(2,i)>2
    reorg(3,i)=reorg(2,i);
    reorg(2,i)=NaN;
   end
   if reorg(3,i)<2
    reorg(3,i)=NaN;
   end
  end
  formant=reorg;

  figure(n)
  hold on
  j=1:42;
  subplot(2,1,1)
  plot(j,(formant(:,j)),'*')

  FORM(in,:,:)=formant;

 end



%---forms model---
clear formmod
for i=1:3
 for j=1:42
   a=find(FORM(:,i,j)>.000001);
   A=FORM(a,i,j);
   formmod(i,j)=sum(A)/length(A);
 end
end

 MOD(n,:,:)=formmod;
 j=1:42;
 subplot(2,1,2)
 plot(j,(formmod(:,j)),'*')

end










