clear
clc
from = uigetdir(pwd, 'Select a folder');
where = uigetdir(pwd, 'Select a folder');
all_files = dir(fullfile(from, '*.mat'));


for j =1:length(all_files)
    file = open(all_files(j,1).name);
    table = file.gTruth.LabelData;
    
   
    
    
    Airplane = table.AIRPLANE;
    Bird = table.BIRD;
    Drone = table.DRONE;
    Helicopter = table.HELICOPTER;
    for i=1:length(Airplane)
        temp = Airplane(i,1);
        temp_A = temp{:};
        temp = Bird(i,1);
        temp_B = temp{:};
        temp = Drone(i,1);
        temp_D = temp{:};
        temp = Helicopter(i,1);
        temp_H = temp{:};
        
        str = "";
        if length(temp_A) == 4
            for k=1:size(temp_A,1)
            x = string((temp_A(k,1)+temp_A(k,3)/2)/640);
            y = string((temp_A(2)+temp_A(k,4)/2)/512);
            w = string(temp_A(k,3)/640);
            h = string(temp_A(k,4)/512);
            str = str+ "0 " +x+ " " +y+ " " +w+ " " +h+ newline;
            end
        end
        
        if length(temp_B) == 4
            for k=1:size(temp_B,1)
            x = string((temp_B(k,1)+temp_B(k,3)/2)/640);
            y = string((temp_B(k,2)+temp_B(k,4)/2)/512);
            w = string(temp_B(k,3)/640);
            h = string(temp_B(k,4)/512);
            str = str+ "1 " +x+ " " +y+ " " +w+ " " +h+ newline;
            end
        end
         
        if length(temp_D) == 4
            for k=1:size(temp_D,1)
            x = string((temp_D(k,1)+temp_D(k,3)/2)/640);
            y = string((temp_D(k,2)+temp_D(k,4)/2)/512);
            w = string(temp_D(k,3)/640);
            h = string(temp_D(k,4)/512);
            str = str+ "2 " +x+ " " +y+ " " +w+ " " +h+ newline;
            end
        end
        
        if length(temp_H) == 4
            for k=1:size(temp_H,1)
            x = string((temp_H(k,1)+temp_H(k,3)/2)/640);
            y = string((temp_H(k,2)+temp_H(k,4)/2)/512);
            w = string(temp_H(k,3)/640);
            h = string(temp_H(k,4)/512);
            str = str+ "3 " +x+ " " +y+ " " +w+ " " +h+ newline;
            end
        end
        
        name_split = split(all_files(j,1).name,'.');
        origin_string = name_split{:};
        origin_name = erase(origin_string,"_LABELS");
        number_name = num2str((i-1),'%07.f');
        new_name = where +"\"+ origin_name +"_"+ number_name +".txt";
        
        
        f_out = fopen(new_name,'w');
        fprintf(f_out,str);
        
        
        fclose(f_out);
        clear file   
    end

   
    
 
    
end
