% Joshua Mack, Sam Bellestri, Nia Simmonds IREECE 2015
% convertPlotAndPSNR_aTanhX:
%   Takes in the test domain used in a given testbench file along with the corresponding exponent and fractional widths of the format and number of iterations
%   And then looks for a corresponding results textfile of the form "(numIters)iterations(expWidth+fracWidth+1)bits_atanh.txt"
%   inside a "FloP_aTanhX_VivadoResults" directory within your current Matlab operating directory.
%   If it doesn't find the file, it displays an error message, and if the file doesn't have the number of points as specified by yPoints,
%   Then it also returns an error and exits. 

function [aTanhPSNR] = convertPlotAndPSNR_aTanhX(yLower, yUpper, yPoints, expWidth, fracWidth, numIters)
    
    % Define a few variables
    dataWidth = expWidth+fracWidth+1;
    q = quantizer('float', [dataWidth expWidth]);
    yRange = linspace(yLower, yUpper, yPoints); 
    
    % Construct the filename we'll be looking for.
    filename = [num2str(numIters), 'iterations', num2str(dataWidth), 'bits_atanh.txt'];
    
    % Attempt to open the file
    file1 = fopen(['./FloP_aTanhX_VivadoResults/', filename], 'r');
    if file1 == -1
        % If it's not found, report an error and return psnr = -123456, an error value used by the corresponding UltimateTestScript file
        % To indicate that a given simulation needs to be repeated.
        display(['aTanh results failed to open for ', num2str(dataWidth), ' bits, ', num2str(numIters), ' iterations.']);
        aTanhPSNR = -123456;
        return;
    end

    % Read the results into a cell array of strings.
    s1 = textscan(file1,'%s');
    fclose(file1);
    
    myATanhStrs = s1{1};

    % If there aren't enough points, report an error and exit with the psnr error value of -123456.
    if length(myATanhStrs) ~= yPoints
        display(['The Vivado simulator failed for ', num2str(dataWidth), ' bits, ', num2str(numIters), ' iterations.']);
        aTanhPSNR = -123456;
        return;
    end
    
    % Allocate memory for the numerical values.
    myATanhs = zeros(yPoints, 1);
    % Extract the numerical values from the strings.
    for i = 1:1:yPoints
        myATanhs(i) = bin2num(q, cell2mat(myATanhStrs(i)));
    end
    
    % Can be used to plot the aTanh values if enabled.
    % figure();
    % plot(yRange, myATanhs); hold on;

    % Allocate memory for the comparison matlab values.
    matlabATanhs = zeros(yPoints, 1);
    % Calculate the corresponding matlab values.
    for i = 1:1:yPoints
        matlabATanhs(i) = atanh(yRange(i));
    end
    
    % For floating point, we use the max as the simple maximum value encountered in the test domain.
    % Calculate the maximum, calculate and display the PSNR, and exit.
    maxATanh = max(atanh(yRange));
    aTanhPSNR = psnr(myATanhs, matlabATanhs, maxATanh);
    fprintf('ATanh PSNR: %f\n\n', aTanhPSNR);
    return;
    
end