%% test written nc files.
close all; clear;

dash_dir = '/glade/work/ldong/DASH/Lin20_DEP_SAPS/';
plt_dir = dash_dir;
% matname = [dash_dir,'fig1_sw.mat'];
% save(matname,'UTday','IMFBy','IMFBz','SYMH','Vsw','Nsw');

    % Prepare for variables to be written to nc file.
    ncname = [dash_dir,'fig1_sw.nc'];
    ncid = netcdf.open(ncname,'NC_NOWRITE'); 
    
    varid = netcdf.inqVarID(ncid,'UTday');   
    UTday = netcdf.getVar(ncid,varid);
    varid = netcdf.inqVarID(ncid,'IMFBy');   
    IMFBy = netcdf.getVar(ncid,varid);
    varid = netcdf.inqVarID(ncid,'IMFBz');   
    IMFBz = netcdf.getVar(ncid,varid);
    varid = netcdf.inqVarID(ncid,'SYMH');   
    SYMH = netcdf.getVar(ncid,varid);
    varid = netcdf.inqVarID(ncid,'Vsw');   
    Vsw = netcdf.getVar(ncid,varid);
    varid = netcdf.inqVarID(ncid,'Nsw');   
    Nsw = netcdf.getVar(ncid,varid);
    
%% Plot
% Canvas
pngname = [plt_dir,'fig1b_sw'];
nrow=5; ncol=1; fpos=[1,39,600,800];
% Parameters
lwid=2; font=12; cl = '';
ttick = UTday(1)+(0:3:24)/24;
xtext = UTday(1)+0.5/24;
tlim=([UTday(1),UTday(end)]);
panlabs = {'(b)','(c)','(d)','(e)','(f)'};
% Plot
fig = figure('position',fpos);
hps{1}=subplot(nrow,ncol,1); hold on; box on;
plot(UTday,Nsw,cl,'LineWidth',lwid);
ylim([0,25]); set(gca,'ytick',0:5:25)
ylabel('N_{SW} [cm^{-3}]');
title('Solar Wind Conditions and SymH');
text(xtext,20,panlabs{1},'FontSize',font,'color','k');
set(gca,'FontSize',font,'xtick',ttick,'XTickLabel',''); 

hps{2}=subplot(nrow,ncol,2); hold on; box on;
plot(UTday,Vsw,cl,'LineWidth',lwid);
ylim([-750,-400]); set(gca,'ytick',-700:100:-400)
ylabel('V_X [km/s]');
text(xtext,-470,panlabs{2},'FontSize',font,'color','k');
set(gca,'FontSize',font,'xtick',ttick,'XTickLabel','','YAxisLocation','right'); 

hps{3}=subplot(nrow,ncol,3); hold on; box on;
plot(UTday,IMFBy,cl,'LineWidth',lwid);
plot(xlim,[0,0],'k--','LineWidth',lwid*0.8);
ylim([-25,20]); set(gca,'ytick',-20:10:20)
ylabel('B_{Y,GSM} [nT]');
text(xtext,11,panlabs{3},'FontSize',font,'color','k');
set(gca,'FontSize',font,'xtick',ttick,'XTickLabel',''); 

hps{4}=subplot(nrow,ncol,4); hold on; box on;
plot(UTday,IMFBz,cl,'LineWidth',lwid);
plot(xlim,[0,0],'k--','LineWidth',lwid*0.8);
ylim([-25,20]); set(gca,'ytick',-20:10:20)
ylabel('B_{Z,GSM} [nT]');
text(xtext,11,panlabs{4},'FontSize',font,'color','k');
set(gca,'FontSize',font,'xtick',ttick,'XTickLabel','','YAxisLocation','right'); 

hps{5}=subplot(nrow,ncol,5); hold on; box on;
plot(UTday,SYMH,cl,'LineWidth',lwid);
ylim([-140,40]); set(gca,'ytick',-140:40:40)
ylabel('SYMH [nT]');
set(gca,'FontSize',font,'xtick',ttick); 
text(xtext,-100,panlabs{5},'FontSize',font,'color','k');
datetick('x','HH:MM','keepticks');
xlabel(datestr(UTday(1),'yyyy-mmm-dd'));

dxc = -0.02; dyc = -0.02; ddy = 0.04;
for ii=1:nrow
    pos=get(hps{ii},'position');
    set(hps{ii},'position',pos+[dxc,dyc,0,ddy]);
end
print(fig,pngname,'-dpng');