clear all
close all

praw=fullfile('..','raw');
pconv=fullfile('..','Processed');

mkdir(pconv)

load(fullfile(praw,'sorted_grids'))

nmax=17;
% find the limits for a greater grid
for i=1:nmax
    
    lims(i,:)=[nanmin(grids.data(i).rawdata.x) nanmax(grids.data(i).rawdata.x) nanmin(grids.data(i).rawdata.y) nanmax(grids.data(i).rawdata.y)];
    
end


flims1=[floor(nanmin(lims(:,1))) ceil(nanmax(lims(:,2))) floor(nanmin(lims(:,3))) ceil(nanmax(lims(:,4)))];

[x2,y2] = convertCoordinates(flims1(1:2),flims1(3:4),'CS1.code',27493,'CS2.code',4326);


flims=[x2(:); y2(:)];

dx=(flims(2)-flims(1))/300;
dy=(flims(4)-flims(3))/300;

% dx=0.5;

x0=flims(1):dx:flims(2);
y0=flims(3):dy:flims(4);

% nx1=400;
% ny1=300;
% 
% [xx,yy,zz]=data2grid2(bathy(:,1),bathy(:,2),bathy(:,3),nx1,ny1,[],[]);

outputfile=fullfile(pconv,'micore_ualg_topogrids.nc');

nc_create_empty(outputfile);

for i=1:nmax
    
    sdate=grids.data(i).date;
    
    [x2,y2] = convertCoordinates(grids.data(i).rawdata.x,grids.data(i).rawdata.y,'CS1.code',27493,'CS2.code',4326);

    [xx,yy,zz,res]=data2grid2(x2,y2,grids.data(i).rawdata.z,[],[],[],[],x0,y0);
    
    figure
    imagesc(res.xl,res.yl,zz)
    
    title(datestr(sdate))
    
%     pause
    
    
    
    if i==1
        
        [nx1,ny1]=size(xx);

        nc_add_dimension(outputfile, 'long', nx1);
        nc_add_dimension(outputfile, 'lat', ny1);
        nc_add_dimension(outputfile, 'time', 1);

        longVariable = struct(...
            'Name', 'long_distance', ...
            'Nctype', 'float', ...
            'Dimension', {{'long', 'lat'}}, ...
            'Attribute', struct('Name', 'unit', 'Value', 'metre') ...
            );
        nc_addvar(outputfile, longVariable);

        latVariable = struct(...
            'Name', 'lat_distance', ...
            'Nctype', 'float', ...
            'Dimension', {{'long', 'lat'}}, ...
            'Attribute', struct('Name', 'unit', 'Value', 'metre') ...
            );
        nc_addvar(outputfile, latVariable);

        timeVariable = struct(...
            'Name', 'year', ...
            'Nctype', 'float', ...
            'Dimension', {{'time'}}, ...
            'Attribute', struct('Name', 'unit', 'Value', 'year') ...
            );
        nc_addvar(outputfile, timeVariable);

        heightVariable = struct(...
            'Name', 'elevation', ...
            'Nctype', 'float', ...
            'Dimension', {{'long', 'lat'}}, ...
            'Attribute', struct('Name', 'unit', 'Value', 'metre') ...
            );
        nc_addvar(outputfile, heightVariable);
        
    end

    
    nc_varput(outputfile, 'elevation', zz)
    nc_varput(outputfile, 'year', sdate)
    nc_varput(outputfile, 'long_distance', xx)
    nc_varput(outputfile, 'lat_distance', yy)

end
% surface(nc_varget(outputfile, 'height')')

nc_dump(outputfile)
