% ----------------------------------------------------------------------- %
% Author: Mireia Leon Dasi
% European Space Agency - ESAC
% Last modified: 07/09/2020
% Description: matlab script to read paths from SBMT files and write the
% latitude and longitude coordinates and path length to excel file
% ----------------------------------------------------------------------- %

clc; clear all; close all;

% Add savepath 
%save_path='';

% Select region
region = 'Seth'

% Input/output files IDs
Input_file = strcat(region,'_Paths');
Output_file = strcat(region,'_Paths.xlsx');
table_path_format = [save_path, Output_file];


% Open and read Input file
fid = fopen(Input_file);
data=textscan(fid,'%s','delimiter','\n', 'HeaderLines', 2 );
fclose(fid);
data = data{1,1};

n_paths = length(data)-1;

% Extract latitude, longitude and length
for i = 1:n_paths
   % Extract text
   text = data{i};
   
   % Read length
   [S,E] = regexp(text, 'length="\d+\.\d+"');
   length(i,1) = round(str2double(text(S+8:E-1))*1000);
   
   %Read latitude and longitude
   [S,E] = regexp(text, 'vertices="-?\d+\.\d+ ');
   lat(i,1) = round(str2double(text(S+10:E-1)),2);
   lon(i,1) = round(str2double(text(E+1:E+16)),2);
   latlong{i,1} =  sprintf('( %.2f , %.2f )', lat(i),lon(i));
   [S,E] = regexp(text, 'name="\w+*?"');
   ID{i,1} = text(S+6:E-1);
end

% Create table with variables
T = table(ID,lat,lon,latlong,length);

% Write data to Excel file
writetable(T,table_path_format,'Sheet',1,'Range','B2')
