% WHOTS 2012 :: 2012-06 :: LB
% Processes daily flux files, makes daily dianostic plots and intermediate
% data files. Averages to 5 and 30 minutes and writes files.
% Calls:
%  read_parameters
%  read_met_day;
%  read_scs_day;
%  read_gps_day; (optionally)
%  read_son_day;
%  read_motion (optionally)
%  read_head (optionally)
%  read_co2
%  read_wave (optionally)\
%  timatch_5;
%  timatch_30;
clear;
close('all');
fclose('all');



%%%%%%%%%%%%%%%%%%%%%%%% Gets day-of-year and year %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~exist('yyyy','var'); yyyy=input('Input year to evaluate as yyyy : ','s'); end;
if ~exist('ddd','var'); ddd=input('Input yearday to evaluate as ddd : '); end;
[m,d]=yd2md(str2num(yyyy), ddd);
Vdate=[str2num(yyyy) m d];

%%%%%%%%%%%%%%%%%%%Modifies current directory and search path%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Fluxroot='D:\WHOTS_2013\Hiialakai\Scientific_analysis\programs\';  % name of the path where the 'flux' folder + read_parameters file are installed.
cd([Fluxroot, 'flux'])         %Changes current directory to fluxroot/flux
addpath(genpath(Fluxroot))     %adds flux folder and all of its subdirectories to the top of the MATLAB search path. 

%%%%%%%%%%%  Read parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
read_parameters_WHOTS_2013;     %reads the parameters for the cruise.
currentMname='WHOTS_2013';
% currentMname=mfilename;   %Gets the name of currently running M-file to pick 
% currentMname=currentMname(17:end);
%eval([ 'read_parameters_', currentMname(11:end)])

%Gets the last uploaded parameter file from Fluxroot directory
dirfluxroot=dir([Fluxroot 'read_parameters_*.m']);
MostrecentPARfile=dirfluxroot(cellfun(@(x) x==max([dirfluxroot.datenum]),{dirfluxroot(:).datenum})).name;
disp(['Most recent parameters being used: ' MostrecentPARfile])
eval(strtok(MostrecentPARfile, '.'));



%%%%%%%%%%%  Defines some options %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
plotit=true; % for making plots. 
prtit=true;  % for printing plots--ineffective unless plotit is also true going to a temp directory
graphformat='.png';  %select graphics format files
graphdevice='-dpng'; %select graphic device
saveit=true; % for saving data files going to a temp directory
clearit=true;% for clearing data sometimes to save memory
report=[];

data_ftp=false;     %to activate ftp to Boulder server
data_backup=false;%true;  %to activate backup to Lacie hardrive (if present)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%****   %double check that all data have been transfered from DAS03 (acquisition) to DAS04         **************
%****   copy raw data folder from D:\Data (on DAS), to way_raw_data_flux (D:\cruise_yyy\ship\flux) **************
if data_backup
    DAS04toDAS03_transfer_checkandcorrect; 
    copyfile(['D:\Data\' yyyy(3:4) sprintf('%03i',ddd)],[way_raw_data_flux yyyy(3:4) sprintf('%03i',ddd)]);
end

%%%%%%%%%%%%%%%%%%%%%%%%% Starts process %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
eval([ 'read_met_day_', currentMname])
%  eval([ 'read_scs_day_', currentMname])   %needs to be checked depending on SCS data system
eval([ 'read_gps_day_', currentMname])
eval([ 'read_head_pitch_day_', currentMname])  
% eval([ 'read_head_roll_day_', currentMname])  
if saveit && exist('gpslat1i','var') && exist('headxi_pitch','var') && ~isempty(gpslat1i) && ~isempty(headxi_pitch)
    eval([ 'prt_jas_gps_', currentMname])
end;
eval([ 'read_son_day_', currentMname])
eval([ 'read_motion_day_', currentMname])
close all;

licor_prefix='lic';
eval([ 'read_co2_day_', currentMname])

% read_whoi_ai_day_WHOTS_2012;

eval([ 'timatch_5_', currentMname])
eval([ 'timatch_30_',currentMname])


% compute radiation with model
if ~exist('gpslat1i','var') && isempty(gpslat1i)
    gpslat1i=ones(length(qvais),1)*NaN;
    gpslon1i=ones(length(qvais),1)*NaN;
end;
jjx=min(length(gpslat1i),length(qvais));
% rlclr=(.515+.13/60*abs(gpslat1i(1:jjx)')+(.082-.03/60.*abs(gpslat1i(1:jjx)')).*sqrt(qvais(1:jjx)')).*(5.67e-8*(Tvais(1:jjx)+273.15).^4);
% rlclr2=(.52+.13/60*abs(gpslat1i')+(.082-.03/60.*abs(gpslat1i')).*sqrt(qvais')+0.0084*4-0.0451).*(5.67e-8*(Tvais(1:jjx)+273.15).^4);
rlclr=(.513+.13/60*abs(gpslat1i(1:jjx)')+(.082-.03/60.*abs(gpslat1i(1:jjx)')).*sqrt(qvais(1:jjx)')).*(5.67e-8*(Tvais(1:jjx)+273.15).^4);

clear jdy;
jdys=jd_pc';
latd=nanmean(gpslat1i);
lond=nanmean(gpslon1i);
qa=qvais; % humidity needed for solar model
iv=ones(length(qa),1)*NaN;

% solar model
eval([currentMname,'_Rsclear_1' ])

%%%%%%%%%%%%%%%%%%%%%%%%% Do plots  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if plotit  %
    if ~isempty(Rhvais(~isnan(Rhvais))) && exist('rhm','var')
        figure;plot(jd_pc,Rhvais,'b',jd_scs,rhm,'g',jd_ai,ai_hrh,'m');axis([ddd ddd+1 50 90])
%         hold on;plot(W9_l1_yday,W9_l1_hrh,'k*--',W9_l2_yday,W9_l2_hrh,'y*--',W8_l1_yday,W8_l1_hrh,'ko--',W8_l2_yday,W8_l2_hrh,'yo--','LineWidth',2)
%         hold on;plot(W9_l1_yday,W9_l1_hrh,'k*--',W9_l2_yday,W9_l2_hrh,'y*--','LineWidth',2)
        title(sprintf('%s (%04i-%02i-%02i, DOY%03i).  PSD/SCS/WHOI relative humidity',cruise,Vdate(1),Vdate(2),Vdate(3),ddd),'FontWeight','Bold','Interpreter','none')
        xlabel('Hour (UTC)');ylabel('Relative Humidity (%)')
%         legend('PSD', 'SCS','WHOI AI','W9 l1','W9 l2','W8 l1','W8 l2','Location','Best');
        legend('PSD', 'SCS','WHOI AI','Location','Best');
        set(gca(gcf),'XTick',ddd:2/24:ddd+1);datetick('x','HH:MM','keepticks');
        xax=get(gca(gcf),'XTickLabel');xax(end,:)='24:00';set(gca(gcf),'XTickLabel',xax(:,1:2))    
        grid
        annotation(gcf,'textbox',[0.007154 0.01077 0.4498 0.02462],'String',{'NOAA/ESRL/PSD/Weather & Climate Physics'},'FontSize',6,'FitBoxToText','off','LineStyle','none'); 
        if prtit; print(graphdevice,[way_images_flux cruise '_PSD-SCS-AI_RH_comparison_' sprintf('%04i_%02i_%02i_%03i',Vdate(1),Vdate(2),Vdate(3),ddd) graphformat]);xlim([ddd ddd+1]); end
    end;

    if exist('Tsea','var') && ~isempty(Tsea(~isnan(Tsea))) && exist('tsgm','var')
        figure;plot(jd_pc,Tsea,'b',jd_scs,tsgm,'g');xlim([ddd ddd+1]);ylim([24 26])
%         hold on;plot(W9_l1_yday,W9_l1_sst,'k*--',W9_l2_yday,W9_l2_sst,'y*--',W8_l1_yday,W8_l1_sst,'ko--',W8_l2_yday,W8_l2_sst,'yo--','LineWidth',2)
%         hold on;plot(W9_l1_yday,W9_l1_sst,'ko--',W9_l2_yday,W9_l2_sst,'yo--','LineWidth',2)
        title(sprintf('%s (%04i-%02i-%02i, DOY%03i).  PSD/SCS sea surface temperature',cruise,Vdate(1),Vdate(2),Vdate(3),ddd),'FontWeight','Bold','Interpreter','none')
        xlabel('Hour (UTC)');ylabel('Sea Temperature (degC)')
%         legend('PSD', 'SCS','W9 l1','W9 l2','W8 l1','W8 l2','Location','Best');
        legend('PSD', 'SCS','Location','Best');
        set(gca(gcf),'XTick',ddd:2/24:ddd+1);datetick('x','HH:MM','keepticks');
        xax=get(gca(gcf),'XTickLabel');xax(end,:)='24:00';set(gca(gcf),'XTickLabel',xax(:,1:2))    
        grid
        annotation(gcf,'textbox',[0.007154 0.01077 0.4498 0.02462],'String',{'NOAA/ESRL/PSD/Weather & Climate Physics'},'FontSize',6,'FitBoxToText','off','LineStyle','none'); 
        if prtit; print(graphdevice,[way_images_flux cruise '_PSD-SCS_Tsea_comparison_' sprintf('%04i_%02i_%02i_%03i',Vdate(1),Vdate(2),Vdate(3),ddd) graphformat]);xlim([ddd ddd+1]); end
    end;

    if ~isempty(Tvais(~isnan(Tvais))) && exist('tam','var')
        figure;plot(jd_pc,Tvais,'b',jd_scs,tam,'g',jd_ai,ai_atmp,'m');xlim([ddd ddd+1])
%         hold on;plot(W9_l1_yday,W9_l1_atmp,'k*--',W9_l2_yday,W9_l2_atmp,'y*--',W8_l1_yday,W8_l1_atmp,'ko--',W8_l2_yday,W8_l2_atmp,'yo--','LineWidth',2)
%         hold on;plot(W9_l1_yday,W9_l1_atmp,'ko--',W9_l2_yday,W9_l2_atmp,'yo--','LineWidth',2)
        title(sprintf('%s (%04i-%02i-%02i, DOY%03i).  PSD/SCS/WHOI air temperature',cruise,Vdate(1),Vdate(2),Vdate(3),ddd),'FontWeight','Bold','Interpreter','none')
        xlabel('Hour (UTC)');ylabel('Air Temperature (degC)')
%         legend('PSD','SCS','WHOI AI','W9 l1','W9 l2','W8 l1','W8 l2','Location','North');ylim([22 28])
        legend('PSD','SCS','WHOI AI','Location','North');ylim([22 28])
        set(gca(gcf),'XTick',ddd:2/24:ddd+1);datetick('x','HH:MM','keepticks');
        xax=get(gca(gcf),'XTickLabel');xax(end,:)='24:00';set(gca(gcf),'XTickLabel',xax(:,1:2))    
        grid
        annotation(gcf,'textbox',[0.007154 0.01077 0.4498 0.02462],'String',{'NOAA/ESRL/PSD/Weather & Climate Physics'},'FontSize',6,'FitBoxToText','off','LineStyle','none'); 
        if prtit; print(graphdevice,[way_images_flux cruise '_PSD-SCS-WHOI_Tair_comparison_' sprintf('%04i_%02i_%02i_%03i',Vdate(1),Vdate(2),Vdate(3),ddd) graphformat]);xlim([ddd ddd+1]); end
    end;

    if ~isempty(press(~isnan(press))) && exist('impresm','var')
        figure;plot(jd_pc,press+0.12*14,'b',jd_scs,impresm+0.12*14.5,'g',jd_ai,ai_bpr+0.12*8.73,'m');xlim([ddd ddd+1])
%         hold on;plot(W9_l1_yday,W9_l1_bpr+0.12*3,'ko--',W9_l2_yday,W9_l2_bpr+0.12*3,'yo--','LineWidth',2)
%         hold on;plot(W9_l1_yday,W9_l1_bpr+0.12*3,'k*--',W9_l2_yday,W9_l2_bpr+0.12*3,'y*--',W8_l1_yday,W8_l1_bpr+0.12*3,'ko--',W8_l2_yday,W8_l2_bpr+0.12*3,'yo--','LineWidth',2)
        title(sprintf('%s (%04i-%02i-%02i, DOY%03i).  PSD/SCS/WHOI barometric pressure',cruise,Vdate(1),Vdate(2),Vdate(3),ddd),'FontWeight','Bold','Interpreter','none')
        xlabel('Hour (UTC)');ylabel('SLP (mb)');ylim([1010 1025])
%         legend('PSD','SCS','WHOI','W9 l1','W9 l2','W8 l1','W8 l2','Location','Best');
        legend('PSD','SCS','WHOI','Location','Best');
        set(gca(gcf),'XTick',ddd:2/24:ddd+1);datetick('x','HH:MM','keepticks');
        xax=get(gca(gcf),'XTickLabel');xax(end,:)='24:00';set(gca(gcf),'XTickLabel',xax(:,1:2))    
        grid
        annotation(gcf,'textbox',[0.007154 0.01077 0.4498 0.02462],'String',{'NOAA/ESRL/PSD/Weather & Climate Physics'},'FontSize',6,'FitBoxToText','off','LineStyle','none'); 
        if prtit; print(graphdevice,[way_images_flux cruise '_PSD-SCS-WHOI_pressure_comparison_' sprintf('%04i_%02i_%02i_%03i',Vdate(1),Vdate(2),Vdate(3),ddd) graphformat]);xlim([ddd ddd+1]); end
    end;

    if ~isempty(rlclr(~isnan(rlclr))) && exist('irm','var')
        ii=find(~isnan(rlclr));
%         figure;plot(jd_pc,pirm,'b',jd_scs,irm,'g',jd_pc(ii),rlclr(ii),'r',jd_ai,ai_LWR,'m');xlim([ddd ddd+1])
        figure;plot(jd_pc,pir1,'b',jd_pc,pir2,'g',jd_pc(ii),rlclr(ii),'r',jd_ai,ai_LWR,'m');xlim([ddd ddd+1])
%         hold on;plot(W9_l1_yday,W9_l1_lwr,'k*--',W9_l2_yday,W9_l2_lwr,'y*--',W8_l1_yday,W8_l1_lwr,'ko--',W8_l2_yday,W8_l2_lwr,'yo--','LineWidth',2)
%         hold on;plot(W9_l1_yday,W9_l1_lwr,'ko--',W9_l2_yday,W9_l2_lwr,'yo--','LineWidth',2)
        title(sprintf('%s (%04i-%02i-%02i, DOY%03i).  PSD/SCS/WHOI infrared flux',cruise,Vdate(1),Vdate(2),Vdate(3),ddd),'FontWeight','Bold','Interpreter','none')
        xlabel('Hour (UTC)');ylabel('IR Flux (W/m^2)')
%         legend('PSD PIR1', 'PSD PIR2','Clearsky','WHOI','W9 l1','W9 l2','W8 l1','W8 l2','Location','Best');
         legend('PSD PIR1', 'PSD PIR2','Clearsky','WHOI','Location','Best');
%         legend('PSD','SCS','WHOI','W9 l1','W9 l2','Location','Best');
        set(gca(gcf),'XTick',ddd:2/24:ddd+1);datetick('x','HH:MM','keepticks');
        xax=get(gca(gcf),'XTickLabel');xax(end,:)='24:00';set(gca(gcf),'XTickLabel',xax(:,1:2))    
        grid
        annotation(gcf,'textbox',[0.007154 0.01077 0.4498 0.02462],'String',{'NOAA/ESRL/PSD/Weather & Climate Physics'},'FontSize',6,'FitBoxToText','off','LineStyle','none'); 
        if prtit; print(graphdevice,[way_images_flux cruise '_PSD-WHOI_IRflux_comparison_' sprintf('%04i_%02i_%02i_%03i',Vdate(1),Vdate(2),Vdate(3),ddd) graphformat]);xlim([ddd ddd+1]); end
    end;

    if ~isempty(Rscl(~isnan(Rscl))) && exist('solarm','var')
        ii=find(~isnan(Rscl));
%         figure;plot(jd_pc,pspm,'.b',jd_scs,solarm,'.g',jd_pc(ii),Rscl(ii),'r');xlim([ddd ddd+1])
        figure;plot(jd_pc,psp1,'.b',jd_pc,psp2,'.g',jd_pc(ii),Rscl(ii),'r',jd_ai,ai_SWR,'m.');xlim([ddd ddd+1])
        hold on;plot(W9_l1_yday,W9_l1_swr,'ko--',W9_l2_yday,W9_l2_swr,'yo--','LineWidth',2)
%         hold on;plot(W9_l1_yday,W9_l1_swr,'k*--',W9_l2_yday,W9_l2_swr,'y*--',W8_l1_yday,W8_l1_swr,'ko--',W8_l2_yday,W8_l2_swr,'yo--','LineWidth',2)
        title(sprintf('%s (%04i-%02i-%02i, DOY%03i).  PSD/SCS solar flux',cruise,Vdate(1),Vdate(2),Vdate(3),ddd),'FontWeight','Bold','Interpreter','none')
        xlabel('Hour (UTC)');ylabel('Solar Flux (W/m^2)')
%         legend('PSD PSP1', 'PSD PSP2', 'Clearsky','WHOI','WHOI','W9 l1','W9 l2','W8 l1','W8 l2','Location','North');ylim([0 1200])
        legend('PSD PSP1', 'PSD PSP2', 'Clearsky','WHOI','WHOI','W9 l1','W9 l2','Location','North');ylim([0 1200])
        set(gca(gcf),'XTick',ddd:2/24:ddd+1);datetick('x','HH:MM','keepticks');
        xax=get(gca(gcf),'XTickLabel');xax(end,:)='24:00';set(gca(gcf),'XTickLabel',xax(:,1:2))    
        grid
        annotation(gcf,'textbox',[0.007154 0.01077 0.4498 0.02462],'String',{'NOAA/ESRL/PSD/Weather & Climate Physics'},'FontSize',6,'FitBoxToText','off','LineStyle','none'); 
        if prtit; print(graphdevice,[way_images_flux cruise '_PSD-WHOI_Solarflux_comparison_' sprintf('%04i_%02i_%02i_%03i',Vdate(1),Vdate(2),Vdate(3),ddd) graphformat]);xlim([ddd ddd+1]); end
    end
end % if plotit

disp(['END of MANUALflux_eval_' currentMname ' yearday ' jd '.']);

%%%%%%%%%%%%%%%%%%%%%%%%% backup raw and processed data to external Lacie hard drive %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if data_backup
    backup_to_Lacie;
end

%%%%%%%%%%%%%%%%%%%%%%%%% ftp selected data to our server %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if data_ftp
    ftp_to_Boulder_v2011;
end       



