%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The main file for the uniformity and the quantum efficiency test    %
%                                                                     %
% Author: Mihai Cara, mcara@purdue.edu                                %
% Last Updated by Mihai Cara on 06/29/2004                            %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clc;
close all;
clear all;

% define constants:
delta_r = 0.5; %the increment used in the radial profile
% delta_sig = 3.6;%the increment used in the azimuthal profile
delta_sig = 10;%the increment used in the azimuthal profile
az_radius = 12.5; %the efective radius 

% Optimization constants:
MaxIter = 2000; % input the number of iterations (for a better accuracy use more 
                % than 250 iterations)
Weighted = 1; % 1 - weighted, 0 - without weights

% OPTIONS:
autoclosefig = 0; % close the plot after it was saved to a file
savefig      = 0; % save the plot:
                  % 0 - do not save;
                  % 1 - save in PNG format
                  % 2 - save in MATLAB FIG format
                  % 3 - save both PNG and FIG formats

% input file:
[fname,pname] = uigetfile('*.txt','Select Test Data File');
if fname == 0
    break;
end

fullname = [pname fname];

fd = fopen([pname fname]);
file_ver = fscanf(fd, 'File Version = %d\n'); %reads the file version
test_mode = fscanf(fd, 'Test Mode: %d'); %reads the test mode
s = fgetl(fd); % file version - the rest of the line

if (file_ver < 1 | file_ver > 4)
    error('This version not supported yet!')
    break;
end

t1=cputime;
switch test_mode  % Chooses the program which has to be run for the desired experiment
case 1
    qe(fd, file_ver);
case 2 % uniformity test (PAM)
    pamunif(fd,file_ver,delta_r,delta_sig,az_radius,MaxIter,Weighted,[]);
case 3 % uniformity test (OPM)
    pamunif(fd,file_ver,delta_r,delta_sig,az_radius,MaxIter,Weighted,[]);
otherwise
    error('Unknown test mode!')
end
t2=cputime;
disp(sprintf('File: %s\nTotal computational time: %g seconds\n', fullname, t2-t1));

% save the result image
[pname,fname,ext,ver] = fileparts(fullname);
switch(savefig)
    case 0
    case 1
        print(gcf, '-dpng', fullfile(pname, [fname '.png' '']));
    case 2
        saveas(gcf, fullfile(pname, [fname '.fig' '']), 'fig');
    case 3
        saveas(gcf, fullfile(pname, [fname '.fig' '']), 'fig');
        print(gcf, '-dpng', fullfile(pname, [fname '.png' '']));
end
if (autoclosefig ==1)
    close(gcf)
end