% extract Eta and S/T/U/V/W for Origins of the Kuroshio-Mindanao Currents
% 13N to 27N, 116E to 128E
% define desired region
region_name='OKMC';
minlat=13;
maxlat=27;
minlon=116;
maxlon=128;
nx=4320;
prec='real*4';
kx=1:90;

% extract indices for desired region
gdir='~dmenemen/llc_4320/grid/';
fnam=[gdir 'Depth.data'];
[fld fc ix jx]=quikread_llc(fnam,nx,1,prec,gdir,minlat,maxlat,minlon,maxlon);
quikpcolor(fld')
thincolorbar

% get and save grid information
close all
pin='~dmenemen/llc_4320/grid/';
pout=['~dmenemen/llc_4320/regions/' region_name '/grid/'];
eval(['mkdir ' pout])
eval(['cd ' pout])
for fnm={'DXC','DXG','DYC','DYG','Depth', ...
         'RAC','RAS','RAW','RAZ', ...
         'XC','XG','YC','YG','hFacC','hFacS','hFacW'}
    fin=[pin fnm{1} '.data'];
    fout=[fnm{1} '_' int2str(length(ix)) 'x' int2str(length(jx))];
    switch fnm{1}
      case{'hFacC','hFacS','hFacW'}
        fld=read_llc_fkij(fin,nx,fc,kx,ix,jx);
        fout=[fout 'x' int2str(length(kx))];
      otherwise
        fld=read_llc_fkij(fin,nx,fc,1,ix,jx);
    end
    writebin(fout,fld);
end

% get and save regional Eta and PhiBot
pin='~dmenemen/llc_4320/MITgcm/run';
pout=['~dmenemen/llc_4320/regions/' region_name '/'];
for fnm={'Eta','PhiBot'}
    eval(['mkdir ' pout fnm{1}])
    eval(['cd ' pout fnm{1}])
    for ts=10368:144:1495008, mydisp(ts)
        if ts<485568
            fin=[pin '/' fnm{1} '.' myint2str(ts,10) '.data'];
        else
            fin=[pin '_485568/' fnm{1} '.' myint2str(ts,10) '.data'];
        end
        dy=ts2dte(ts,25,2011,9,10,30);
        fout=[fnm{1} '_' int2str(length(ix)) 'x' int2str(length(jx)) '.' dy];
        fld=read_llc_fkij(fin,nx,fc,1,ix,jx);
        writebin(fout,fld);
    end
end

% get and save regional S/T/U/V/W
for fnm={'Salt','Theta','U','V','W'}
    eval(['mkdir ' pout fnm{1}])
    eval(['cd ' pout fnm{1}])
    for ts=10368:144:1495008, mydisp(ts)
        if ts<485568
            fin=[pin '/' fnm{1} '.' myint2str(ts,10) '.data'];
        else
            fin=[pin '_485568/' fnm{1} '.' myint2str(ts,10) '.data'];
        end
        dy=ts2dte(ts,25,2011,9,10,30);
        fout=[fnm{1} '_' int2str(length(ix)) 'x' int2str(length(jx)) ...
              'x' int2str(length(kx)) '.' dy];
        for k=1:length(kx); mydisp(k)
            fld=read_llc_fkij(fin,nx,fc,kx(k),ix,jx);
            writebin(fout,fld,1,'real*4',k-1);
        end
    end
end
