% Extract daily mean SST, SSS, and SSH, and daily maximum KPPhbl

% define desired region
region_name='IndoPac';
minlat=-30;
maxlat=35;
minlon=19;
maxlon=300;

% extract indices for desired region
nx=2160;
prec='real*4';
gdir='~dmenemen/llc_2160/grid/';
fnam=[gdir 'Depth.data'];
[tmp fc ix jx] = ...
    quikread_llc(fnam,nx,1,prec,gdir,minlat,maxlat,minlon,maxlon);
m(1)=0;
for f=1:length(fc)
    m(f+1)=length(ix{fc(f)});
end
n=length(jx{fc(1)});
fld=zeros(sum(m),n);
for f=1:length(fc)
    fld((sum(m(1:f))+1):sum(m(1:(f+1))),:)=tmp{fc(f)};
end
quikpcolor(fld')

% Get and save grid information
close all
pout=['~dmenemen/llc_2160/regions/' region_name '/grid/'];
eval(['mkdir ' pout])
eval(['cd ' pout])
for fnm={'AngleCS','AngleSN','DXC','DXG','DYC','DYG','Depth', ...
         'RAC','RAS','RAW','RAZ','U2zonDir','V2zonDir', ...
         'XC','XG','YC','YG','hFacC','hFacS','hFacW'}
    fin=[gdir fnm{1} '.data'];
    fout=[fnm{1} '_' int2str(sum(m)) 'x' int2str(n)];
    for f=1:length(fc)
        fld((sum(m(1:f))+1):sum(m(1:(f+1))),:) = ...
            read_llc_fkij(fin,nx,fc(f),1,ix{fc(f)},jx{fc(f)});
    end
    writebin(fout,fld);
end

% get and save regional fields
pin='~dmenemen/llc_2160/regions/global/';
pout=['~dmenemen/llc_2160/regions/' region_name '/'];
fn1={'Theta_daily/Theta_2160x28080.','Eta_daily/Eta_2160x28080.'};
fnm={'SST','SSH'};
for i=1:length(fnm)
    eval(['mkdir ' pout fnm{i}])
    eval(['cd ' pout fnm{i}])
    for ts=datenum(2011,3,6):datenum(2013,4,22)
        dy=datestr(ts,30);
        fin=[pin fn1{i} dy];
        fout=[fnm{i} '_' int2str(sum(m)) 'x' int2str(n) '.' dy];
        disp(fout)
        for f=1:length(fc)
            fld((sum(m(1:f))+1):sum(m(1:(f+1))),:) = ...
                read_llc_fkij(fin,nx,fc(f),1,ix{fc(f)},jx{fc(f)});
        end
        writebin(fout,fld);
    end
end
