clear all;

%% STEP 1: Add a unique gridID to your FEWS grid and save as csv file to be processed in QGIS

% Read lat and lon coordinates from your netcdf:
lat = ncread('/Users/wiebkejager/checkouts/risckit/BNAdaptor/trainingData/run1/hazard.nc','lat');
lon = ncread('/Users/wiebkejager/checkouts/risckit/BNAdaptor/trainingData/run1/hazard.nc','lon');

% If applicable, i.e. using a structured grid, reshape grid matrices to vectors (necessary to be readible by a GIS software)
dimlat = size(lat);
dimlat = dimlat(1) *dimlat(2);
dimlon = size(lon);
dimlon = dimlon(1) *dimlon(2);
Lat = reshape(lat',dimlat,1);
Lon = reshape(lon',dimlon,1);

% Associate gridID with each set of coordinates
gridID = (1:length(Lat))';
coordinates = table(Lon,Lat,gridID);

% Write lat, lon and gridID vector to text file that can be opened in a GIS
% software
% writetable(coordinates,'FEWSGrid')


%% STEP 2: Create a <receptor>.csv in a GIS software

%% STEP 3: Test <receptor>.csv file created in QGIS against your grid.

% Open your csv file
IDs = csvread('ResBuildings.csv',1,0);

% Sort so that receptorIDs are ascending.
IDs = sortrows(IDs,2);


% Check if the gridIDs are correctly assigned
areas = unique(IDs(:,1));
cmap = hsv(length(areas));  
figure
for i = 1:length(areas)   
    grid_ind = IDs(logical(IDs(:,1) == areas(i)),3);
    Lat(grid_ind)
    plot(Lat(grid_ind),Lon(grid_ind),'o','Color',cmap(i,:))
    hold on
end

%% STEP 4: Save as <receptor.csv> file to be saved in workDir for the BN Adaptor

% Save with filename as ID of the corresponding hazard variable (see your Hnodes.json file)
dlmwrite('/Users/wiebkejager/checkouts/risckit/BNAdaptor/workDir/ResBuildings.txt',IDs,'delimiter','\t','precision',10) 