clear 
close all 
clc

GT_Filename = 'videoX_GT.txt';
TrialM1_T0_S0 = 'videoX_OTout.txt';

[Actual_GT_ALL,delimiterOutGT] = importdata(GT_Filename);  
GT = Actual_GT_ALL(1:end,:);

[M1_T0_S0,delimiterOutM10] = importdata(TrialM1_T0_S0);  
Cal = M1_T0_S0; 
Len = size(Cal,1); 

AOA_ALL_Frames = zeros(Len,1);
CLE_ALL_Frames = zeros(Len,1);
FR_ALL_Frames = zeros(Len,1);
Cal = M1_T0_S0;          
    
% Calculate the Overlap Areas =============================================    
Overlap_Areas = zeros(Len,1);    
Failure_Rates = zeros(Len,1);

for i=1:Len
    XMin_GT = GT(i,1);
    XMin_Cal = Cal(i,1);

    XMax_GT = GT(i,1) + GT(i,3);
    XMax_Cal = Cal(i,1) + Cal(i,3);

    YMin_GT = GT(i,2);
    YMin_Cal = Cal(i,2);

    YMax_GT = GT(i,2) + GT(i,4);
    YMax_Cal = Cal(i,2) + Cal(i,4);

    x0 = max( XMin_GT ,  XMin_Cal );
    x1 = min( XMax_GT ,  XMax_Cal );
    y0 = max( YMin_GT ,  YMin_Cal );
    y1 = min( YMax_GT ,  YMax_Cal );

    if (x0 >= x1 || y0 >= y1) 
        Overlap_Areas(i) = 0;
    else
        areaInt = (x1-x0)*(y1-y0);
        Area_GT = GT(i,3) * GT(i,4);
        Area_Cal = Cal(i,3) * Cal(i,4);
        Overlap_Areas(i) = areaInt / (Area_GT + Area_Cal - areaInt);
    end        

    if Overlap_Areas(i) == 0                      
        Failure_Rates(i) = 1;                     
    end
end

AOA_ALL_Frames(1:Len) = Overlap_Areas;
Mean_AOA_ALL_Frames = mean(AOA_ALL_Frames);

FR_ALL_Frames(1:Len) = Failure_Rates;    
Mean_FR_ALL_Frames = mean(FR_ALL_Frames);

% Calculate Center Location Error =================================
AVG_CLE = 0;    
CLE_Cal = zeros(Len,1);
for i=1:Len  
    XI = Cal(i,1) +  (Cal(i,3)/2);
    YI = Cal(i,2) +  (Cal(i,4)/2);
    XI_GT = GT(i,1) +  (GT(i,3)/2);
    YI_GT = GT(i,2) +  (GT(i,4)/2);

    CLE_Cal(i,1) = sqrt( (XI-XI_GT)^2 + (YI-YI_GT)^2 );
    AVG_CLE = AVG_CLE + sqrt( (XI-XI_GT)^2 + (YI-YI_GT)^2 );         
end

CLE_ALL_Frames(1:Len) = CLE_Cal;
Mean_CLE_ALL_Frames = mean(CLE_ALL_Frames);

Final_AOR = Mean_AOA_ALL_Frames
Final_CLE = Mean_CLE_ALL_Frames
Final_FR = Mean_FR_ALL_Frames         
