% extract variables in WESTPAC experiment area

% define desired region

prec='real*4';
nx=2160;
region_name='Stratus';
minlon= -85.14-1/23;
maxlon= -85.14+1/23;
minlat= -20.15-1/23;
maxlat= -20.15+1/23;
kx=1:7;

% extract indices for desired region
prec='real*4';
gdir=['/u/dmenemen/llc_' int2str(nx) '/grid/'];
pin = gdir;
fnam=[pin '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
pout=['/u/dmenemen/llc_' int2str(nx) '/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=[pin fnm{1} '.data'];
    fout=[fnm{1} '_' int2str(length(ix)) 'x' int2str(length(jx))];
    switch fnm{1}
      case{'RC','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 S/T
pn='/u/dmenemen/llc_2160/MITgcm/run';
pout=['/u/dmenemen/llc_2160/regions/' region_name '/'];
for fnm={'U','V'}
    eval(['mkdir ' pout fnm{1}])
    %eval(['cd ' pout fnm{1}])
    for ts=92160:80:1586400
%    for ts=1486080:80:1586400
        if (ts<1198080)
            pin=[pn '_day49_624/'];
        else
            pin=[pn '/'];
        end
        fin=[pin fnm{1} '.' myint2str(ts,10) '.data'];
        dy=ts2dte(ts,45,2011,1,17,30);
        fout=[pout fnm{1} '/' fnm{1} '_' int2str(length(ix)) 'x' int2str(length(jx)) ...
              'x' int2str(length(kx)) '.' dy];
        disp(fout)
        for k=7
            fld=read_llc_fkij(fin,nx,fc,kx(k),ix,jx);
            writebin(fout,fld,1,'real*4',6);
        end
    end
end