%matlab script to plot comparator response time spread
%after monte carlo simulation of transistor variation in
%IBM cmrf8sf 130 nm process

   %initialize M once, then comment out to save time
   %to save time: select on interesting regions when exporting
   %to csv file.
   clear T;
   clear M;
   clear N;
   clear P;
   clear O;
   M = csvread('adccomp_1.csv', 1, 0);
   %N = csvread('comp2.csv', 1, 0);
   %P = csvread('comp3.csv',1,0);
   %O = csvread('comp4.csv',1,0);
    
    [rows, cols] = size(M);
    %[rows1,cols1] = size(N);
    %[rows2,cols2] = size(P);
    %[rows3, cols3] = size(O);
    fprintf('rows = %d columns = %d\n', rows, cols);
    %fprintf('rows = %d columns = %d\n', rows1, cols1);
    %fprintf('rows = %d columns = %d\n', rows2, cols2);
    
    th = 2.0000E-6;
    % data in matrix T
    for n0 = 2:cols,
       % fprintf('iteration = %d\n', n); 
        
        for m0 = 1:rows,
       
            if M(m0,n0) > 0.6,
                T(n0-1) = M(m0,1)-th;
        %       fprintf('#=%d time = %d\n', n-1, T(n-1));
                break;
            end
        end
    end
   fprintf('size T now = %d\n', size(T)); 
%{
   % add second round of data to T
    for n1 = 2:cols1,
        %fprintf('iteration = %d\n', i); 
        
        for m1 = 1:rows1,
       
            if N(m1,n1) > 0.6,
                T(n1+cols-2) = N(m1,1)-th;
         %      fprintf('# = %d time = %d\n',i+cols-2, T(i+cols-2));
                break;
            end
        end
    end
   fprintf('size T now = %d\n', size(T));
  
   for n2 = 2:cols2,
        %fprintf('iteration = %d\n', i); 
        
        for m2 = 1:rows2,
       
            if P(m2,n2) > 0.6,
                T(n2+cols+cols1-3) = P(m2,1)-th;
         %      fprintf('# = %d time = %d\n',i+cols-2, T(i+cols-2));
                break;
            end
        end
   end
    fprintf('size T now = %d\n', size(T)); 
    
   for n3 = 2:cols3,
        %fprintf('iteration = %d\n', i); 
        
        for m3 = 1:rows3,
       
            if O(m3,n3) > 0.6,
                T(n3+cols+cols1+cols2-4) = O(m3,1)-th;
         %      fprintf('# = %d time = %d\n',i+cols-2, T(i+cols-2));
                break;
            end
        end
   end
    fprintf('size T now = %d\n', size(T));
    
   %}

   %hist(T, 60)
   

   histfit(T, 20);

   xlabel('Comparator Response Time (s)'); ylabel('Counts');
   
   %check gaussian
  %{ 
   hold on;
   u = 1.72E-8;
   syms x;
   max = 22;
   sigma = 9.75E-9;
   f = max*exp(-(x-u)^2/(2*sigma^2));
   ezplot(f, [0, 4.5E-8]);
   hold off;
   %}
