function Comp(varargin)
%
% version  20-April-2002
% 1. Comparison of the tubes characteristics.
% 2. Calculating the tube parameters.
% 3. Plots of a tube characteristics. 
%                  The data file format 
% File name  ---> 6N8C.dat
% Name='6N8C'; Type='Triode'; %or Pentode
% Up=[....];
% Ug=[....];
% Ip=[....];
% Us=[]; 	%for pentode
%
% Copyright (C) 2002 by Eugene V. Karpov. The author assumes no legal 
% liability arising from the use of this program.
% E-mail k.nexttube@gmail.com


global Ip Ug Up Type fname Us

Us=[];
Type='';
Ugstep=-1;									%Default Ug step

%Initial axis value
Imax=0;
Upmin=0;
Upmax=0;
Base=cell(6,10);
%Number of tube
N=1;
%Load data file
while 1
	[fname,pname] = uigetfile('*.dat');	%Selection data file
	if isempty(findstr(fname,'.dat'))
   	error('File not selected');
	end
	fid=fopen(fname,'rt');					%Open data file
	if fid<0
   	error('Do not reading');
	end
	while 1  line = fgetl(fid);			%Load data file 
   	if ~isstr(line)
      	break 
   	end
   eval(line,'fprintf(''%s%s\n'',12,lasterr);');
	end; 
	fclose(fid);
	%Check data
	errmes1='Shortage data'; 
	if length(Up)~=length(Ug); error(errmes1); end
	if length(Up)~=length(Ip); error(errmes1); end

	%Check tube type
	switch Type;
     case 'Pentode',...
     if isempty(Us); error([errmes1,' Us.']); end,...		%Check data
     %if length(Up)~=length(Us); error(errmes1); end,...	%Check data
     case 'Triode',
  	otherwise
     clear
         error('Absence tube Type')
  	end
      
	% Calculation axis value     
	if max(Ip)>Imax;
   	Imax=max(Ip);
	end
	if max(Up)>Upmax;
   	Upmax=max(Up);
	end
	if Upmin==0;
   	Upmin=min(Up);
	elseif Upmin>min(Up);
   	Upmin=min(Up);
	end
      
	%Save data
	Base{1,N}=Up; Base{2,N}=Us; Base{3,N}=Ug; Base{4,N}=Ip; 
   Base{5,N}=Name; Base{6,N}=Type;
   
   Amount=['Input data',sprintf('\n'),'N=',sprintf('%1.f',N)];
	select=menu(Amount,'Next tube','Done');  %Load next tube
   if  select==1;
   	if N<100
         N=N+1;
      else
         h = msgbox('The maximum quantity is loaded','WARNING','warn');
      	waitfor(h);
			break;
      end  
      else
         break;
   end;
end

cm=['k','b','m','r','g'];		%COLOR MAP	
Nmax=N;								%Tubes amount 
point1=0;							%Temporary
%Choice mode
num=1:1:Nmax; 
while 1
	while 2
	select=menu('Select Action','Plot data','Calculation parameters',...  
   'Compare','Clear','Quit');
	if isempty(select);
   	close all;
   	clear
    	error('Break-down Calculation')
    elseif select==1;
       
    %Tube number
    	N=listdlg('PromptString','Select a tube:','SelectionMode',...
   				'single','ListSize',[100 200],'ListString',num);
     	if isempty(N); break; end;
   	if N==0; break; end;
     	UG=Base{3,N}; UP=Base{1,N}; IP=Base{4,N};		%Extract data
		[UgS,i,j]=unique(UG); UgS=rot90(UgS,2);		%Gride voltage
		i=rot90(i,2);
		first=cell(2,length(i));							% Sort data 	
		for p=1:1:length(i);
   		if p==1
      		first{1,p}=UP(1:i(p));
      		first{2,p}=IP(1:i(p));
   		else
      		first{1,p}=UP(i(p-1)+1:i(p));
      		first{2,p}=IP(i(p-1)+1:i(p));
   		end
		end
   	if point1==0;
      	figure(1);
			grid on;
			hold on;
			axis([Upmin Upmax 0 Imax]); xlabel('Up'); ylabel('Ip');
      end
      point1=point1+1;
      if point1>5;
         point1=1;
      end
      for p=1:1:length(i);
   		U = [min(first{1,p}):max(first{1,p})];
   		plot(U,spline(first{1,p},first{2,p},U),cm(point1));
   		plot(first{1,p},first{2,p},'rx');
      end
      clear U; clear first;
	elseif select==2;
      %Calculation parameters
      close all;
      %Tube number
      N=listdlg('PromptString','Select a tube:','SelectionMode',...
   				'single','ListSize',[100 200],'ListString',num);
     	if isempty(N); break; end;
   	if N==0; break; end;
     	UG=Base{3,N}; UP=Base{1,N}; IP=Base{4,N};		%Extract data
		[UgS,i,j]=unique(UG); UgS=rot90(UgS,2);		%Gride voltage
      i=rot90(i,2);
      if length(i)<4;
         h = msgbox(' It is not enough of the data','WARNING','warn');
         waitfor(h);
         close all;
         break;
      end
      first=cell(2,length(i));							% Sort data 	
		for p=1:1:length(i);
   		if p==1
      		first{1,p}=UP(1:i(p));
      		first{2,p}=IP(1:i(p));
   		else
      		first{1,p}=UP(i(p-1)+1:i(p));
      		first{2,p}=IP(i(p-1)+1:i(p));
   		end
      end
      %Plot data 
		numb1=sprintf('%1.f',N);
		figure(1);
		grid on;
		hold on;
		axis([Upmin Upmax 0 Imax]); xlabel('Up'); ylabel('Ip');...
   	title(['Tube  ',Base{5,N},'   Number ',numb1,]);
		for p=1:1:length(i);
   		U = [min(first{1,p}):max(first{1,p})];
   		plot(U,spline(first{1,p},first{2,p},U),'b');
   		plot(first{1,p},first{2,p},'rx');
      end
      %Select a gride voltage
      Ng=listdlg('PromptString','Gride voltage:','SelectionMode',...
   				'single','ListSize',[100 200],'ListString',UgS(2:length(UgS)-1));
     	if isempty(Ng);	close all; point1=0; break; end;
      if Ng==0; close all; point1=0; break; end;
      %Highlight curve  
   	U = [min(first{1,Ng+1}):max(first{1,Ng+1})];
      plot(U,spline(first{1,Ng+1},first{2,Ng+1},U),'r');
      %Point for calculation 
      x=[]; y=[];
    	while isempty(x)
       	[x,y]=ginput;
       end
       x=x(length(x));
       y=y(length(y));
      if x>max(first{1,Ng+1});
         h = msgbox('          Out of range','ERROR','error');
         waitfor(h);
         close all;
         break;
      elseif x<min(first{1,Ng+1});
         h = msgbox('          Out of range','ERROR','error');
         waitfor(h);
         close all;
         break;
      end
      y=spline(first{1,Ng+1},first{2,Ng+1},x);
      plot(x,y,'kx','MarkerSize',20);
      %Calculation Ri
      Ri=1./(spline(first{1,Ng+1},first{2,Ng+1},x+1)-...
         spline(first{1,Ng+1},first{2,Ng+1},x));
      %Calculation S
      S=(spline(first{1,Ng+2},first{2,Ng+2},x)-...
         spline(first{1,Ng},first{2,Ng},x))./(UgS(Ng+2)-UgS(Ng));
      %
      M=S.*Ri;
      disp(['Tube N',sprintf('%2.f',N),' ',Base{5,N},' ',Base{6,N},' Ug=',sprintf('%2.1f',UgS(Ng+1)),'V',...
            ' Ip=',sprintf('%3.1f',y.*1000),'mA','    Ri=',sprintf('%4.2f',Ri./1000),...
            'kOhm',' S=',sprintf('%3.1f',S.*1000),'mA/V',' Mu=',sprintf('%2.1f',M)]);

		text(Upmin+Upmax./100,Imax-Imax./50,['Ri=',sprintf('%4.2f',Ri./1000),'kOhm',...
   			' S=',sprintf('%3.1f',S.*1000),'mA/V',' Mu=',sprintf('%2.1f',M)]);
      
           
   elseif select==3;
      %Compare
      close all;
      N=1;
      NAME=Base{5,N};      
      if Nmax==1; 
         h = msgbox('Is not present data for comparison','WARNING','warn');
         waitfor(h);
         break;
      end;
      h = waitbar(0,'Please wait...');
      R=ones(Nmax-1,Nmax-1).*500;		%Result of comparison
         for N=1:1:Nmax-1;
         %Data of a first tube
         UG=Base{3,N}; UP=Base{1,N}; IP=Base{4,N};
         NAME1=Base{5,N};
         if strcmp(NAME,NAME1);		%Compare name
            [UgS,i,j]=unique(UG); UgS=rot90(UgS,2);
         	i=rot90(i,2);
         	first=cell(2,length(i));
				for p=1:1:length(i);
   				if p==1
      				first{1,p}=UP(1:i(p));
      				first{2,p}=IP(1:i(p));
   				else
      				first{1,p}=UP(i(p-1)+1:i(p));
      				first{2,p}=IP(i(p-1)+1:i(p));
   				end
				end
         	%Data of a second tube 
         	for z=N+1:1:Nmax				%Step by tube
         		UG2=Base{3,z}; UP2=Base{1,z}; IP2=Base{4,z};
         		NAME2=Base{5,z};
         		if strcmp(NAME1,NAME2);		%Compare name
            		if UG==UG2;			%Compare gride voltage
               		[UgS2,i2,j2]=unique(UG2); UgS2=rot90(UgS2,2);
                  	i2=rot90(i2,2);
                 		second=cell(2,length(i2));
							for p=1:1:length(i2);
   							if p==1
      							second{1,p}=UP2(1:i2(p));
      							second{2,p}=IP2(1:i2(p));
   							else
      							second{1,p}=UP2(i2(p-1)+1:i2(p));
      							second{2,p}=IP2(i2(p-1)+1:i2(p));
   							end
                  	end
                  	%Compare data
                  	clear U; 
                  	for u=1:1:length(i)					%Step by gride xoltage
                     	Ucmin=min(first{1,u});
                     	Ucmax=max(first{1,u});
                     	if first{1,u}~=second{1,u};	%Fit plate voltage
                        	if min(first{1,u})>min(second{1,u});
                           	Ucmin=min(first{1,u});
                       		else
                           	Ucmin=min(second{1,u});
                       	 end
                        	if max(first{1,u})>max(second{1,u});
                           	Ucmax=max(second{1,u});
                        	else
                           	Ucmax=max(first{1,u});
                        	end
                     	end
                     	U=[Ucmin:Ucmax];
                     	I1=spline(first{1,u},first{2,u},U);			%Generate curve
                     	I2=spline(second{1,u},second{2,u},U);
                     	r(u)=max(abs(1-I1./I2));				%Compare
                     	clear I1; clear I2; clear U;
                  	end	%End - one tube
                  	R(N,z-1)=max(r).*100; %%%%%%%%
       				end	%End compare - gride voltage
            	end  %End compare - name
            end % End compare - one column
            
         	clear first; clear second;
         	%disp(sprintf('%1.f',N));
            %disp(sprintf('%1.f',z));
         end
         waitbar(N./(Nmax-1));
      end % End compare
      close(h);
      if R==0; 
         h = msgbox('Is not present data for comparison','WARNING','warn');
         waitfor(h);
         break; end;
      %Sort data
      [x,y]=find(R>0 & R<=min(min(R))); %Better pair
      disp(sprintf('\n'));
		disp(['Tube  ',Name,' ',Base{6,N},'     ',date]);
       disp(['Best pair is tubes ',sprintf('%1.f',x),' and ',sprintf('%1.f',y+1),...
            ', accuracy ',sprintf('%2.2f',R(x,y)),'%']);
      [x1,y1]=find(R>0 & R<=5);	% 5% accuracy
      y1=y1+1;
      disp(' 5% accuracy');
      if isempty(x1); disp('	None'); end
      disp(rot90(x1));
      disp(rot90(y1));
      [x2,y2]=find(R>5 & R<=10);				% 10% accuracy
      y2=y2+1;
      disp(' 10% accuracy');
      if isempty(x2); disp('	None'); end
      disp(rot90(x2));
      disp(rot90(y2));
      [x3,y3]=find(R>10 & R<=20);			% 20% accuracy
      y3=y3+1;
      disp(' 20% accuracy');
      if isempty(x3); disp('	None'); end
      disp(rot90(x3));
      disp(rot90(y3));
      %Plot Better pair
      tmp=[x y+1];
      numb1=sprintf('%1.f',x);
		numb2=sprintf('%1.f',y+1);
		figure(1);
		grid on;
		hold on;
		axis([Upmin Upmax 0 Imax]); xlabel('Up'); ylabel('Ip');...
   	title(['Tube  ',Base{5,x},'   Best pair  ',numb1,' and ',numb2]);
      for u=1:2;
         N=tmp(u);
         UG=Base{3,N}; UP=Base{1,N}; IP=Base{4,N};
			[UgS,i,j]=unique(UG); UgS=rot90(UgS,2);		%Gride voltage
      	i=rot90(i,2);
      	first=cell(2,length(i));
			for p=1:1:length(i);
   			if p==1
      			first{1,p}=UP(1:i(p));
      			first{2,p}=IP(1:i(p));
   			else
      			first{1,p}=UP(i(p-1)+1:i(p));
      			first{2,p}=IP(i(p-1)+1:i(p));
   			end
			end
			for p=1:1:length(i);
   			U = [min(first{1,p}):max(first{1,p})];
   			plot(U,spline(first{1,p},first{2,p},U),'b');
   			plot(first{1,p},first{2,p},'rx');
         end
         clear U; clear first;
      end
      break;                            
	elseif select==4;
   	close all;
   	point1=0;
	else
   	close all;
   	clear;
   	return;
	end
end
end

