% flux_eval_Xcruise2009
% Xcruise 2009 :: 2009-09-07 :: 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');


%try
   
    %%%%%%%%%%%%%%%%%%%%%%%% Gets day-of-year and year %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%     ddd=180
    if ~exist('yyyy','var'); yyyy=input('Input year to evaluate.... ','s'); end;
    if ~exist('ddd','var'); ddd=input('Input yearday to evaluate.... '); end;
    
    
    %%%%%%%%%%%%%%%%%%%Modifies current directory and search path%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    Fluxroot='D:\CALNEX_2010\Atlantis\AUTOFlux_programs_v2\';  % name of the path where the 'flux' folder + read_parameters file are installed.
    addpath(genpath(Fluxroot))     %adds flux folder and all of its subdirectories to the top of the MATLAB search path. 
    dataroot='D:\Data\';  % name of the path where the 'flux' folder + read_parameters file are installed.
    %%%%%%%%%%%  Read parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
     %read_parameters_RHB_2009;     %reads the parameters for the cruise.
     cd([dataroot])         %Changes current directory to fluxroot/flux
     read_parameters_MANUAL_09;     %reads the parameters for a Manual check of data, nothing saved.
    cd([Fluxroot, 'flux'])         %Changes current directory to fluxroot/flux
%      currentMname=mfilename;   %Gets the name of currently running M-file to pick 
      currentMname='CALNEX_2010';   %Gets the name of currently running M-file to pick 
% %     eval([ 'read_parameters_', currentMname(11:end)])
%     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, '.'));
    
    [m,d]=yd2md(str2num(yyyy), ddd);
    Vdate=[str2num(yyyy) m d];
    
    %%%%%%%%%%%  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;  %to activate backup to Lacie hardrive (if present)
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    %****   copy raw data folder from D:\Data (on DAS), to way_raw_data_flux (D:\cruise_yyy\ship\flux) **************
    if data_backup
        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])
    eval([ 'read_gps_day_', currentMname])
    eval([ 'read_head_day_', currentMname])  
    eval([ 'read_son_day_', currentMname])
    eval([ 'read_motion_day_', currentMname])
    licor_prefix='lic';
    eval([ 'read_' 'co2_', currentMname])
    % read_wave_day_Xcruise_2009;

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

    % compute radiation with model
    jjx=min(length(latm),length(qvais));
    rlclr=(.52+.13/60*abs(latm(1:jjx))+(.082-.03/60.*abs(latm(1:jjx))).*sqrt(qvais(1:jjx)')).*(5.67e-8*(Tvais(1:jjx)+273.15).^4);

    clear jdy;
    jdys=jd_pc';
    latd=nanmean(latm);
    lond=nanmean(lonm);
    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)))
            figure;plot(jd_pc,Rhvais,'b',jd_scs,rhm,'.g');axis([ddd ddd+1 0 100])
            title(sprintf('%s (%04i-%02i-%02i, DOY%03i).  PSD/SCS relative humidity',cruise,Vdate(1),Vdate(2),Vdate(3),ddd),'FontWeight','Bold','Interpreter','none')
            xlabel('Hour (UTC)');ylabel('Relative Humidity (%)')
            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_RH_comparison_' sprintf('%04i_%02i_%02i_%03i',Vdate(1),Vdate(2),Vdate(3),ddd) graphformat]);xlim([ddd ddd+1]); end
        end;
        
        if ~isempty(Tsea(~isnan(Tsea)))
            figure;plot(jd_pc,Tsea,'b',jd_scs,tsgm,'.g');xlim([ddd ddd+1])
            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','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)))
            figure;plot(jd_pc,Tvais,'b',jd_scs,tam,'.g');xlim([ddd ddd+1])
            title(sprintf('%s (%04i-%02i-%02i, DOY%03i).  PSD/SCS air temperature',cruise,Vdate(1),Vdate(2),Vdate(3),ddd),'FontWeight','Bold','Interpreter','none')
            xlabel('Hour (UTC)');ylabel('Air Temperature (degC)')
            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_Tair_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)))
            ii=find(~isnan(rlclr));
            figure;plot(jd_pc,pirm,'b',jd_scs,irm,'g',jd_scs(ii),rlclr(ii),'r');xlim([ddd ddd+1])
            title(sprintf('%s (%04i-%02i-%02i, DOY%03i).  PSD/SCS 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', 'SCS', 'Clearsky','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_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)))
            ii=find(~isnan(Rscl));
            figure;plot(jd_pc,pspm,'.b',jd_scs,solarm,'.g',jd_pc(ii),Rscl(ii),'r');xlim([ddd ddd+1])
            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', 'SCS','Clearsky','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_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_v3;
    end       



