% VOCALS 2008 :: 2008-10-16 :: Dan Wolfe
% modified by Simon de Szoeke
% Read 1-minute Kipp and Zonen radiometers
% processed by the Campbell Scientific data logger.
disp(['read_kz_day: ', cruise, ' ', year]);
fclose('all');
jd=sprintf('%03i',ddd);

clear
close all
fclose('all');

read_parameters;
% inherit prtit and saveit
%prtit=true
%saveit=true

% modified on 30-mar-01 by D.E.Lane for Kai 2001 cruise
% modified 10 nov 03 by cfairall for the weller 2003 cruise
% modified 09 jul 04 by hare
% modified April 06 by lbariteau for the AMMA 2006 cruise (changement of
% the variables in the Mean Campbell datalogger)
read_parameters;
disp(['read_kzr_day: ' cruise year])
if ~exist(ddd,'var');
    dddb=input('Input start yearday to evaluate.... ');
    ddde=dddb;
end

read_parameters; %Reading parameter files flux

for ddd = dddb:ddde  % option to loop throuh all the days
    jd=sprintf('%03i',ddd);
    
    clear jad;
    hr='00';							%input('gmt hr','s');
    g=0.0098;						    %adiabatic lapse rate
    eps_w=0.97;						    %emissivity of water
    sig_sb=5.67e-8;				        %Stefan Boltzmann constant
    blk=1;							    %10-min index
    jax=1;
    backchk=0;
    clear st2
    total_num_fields=72;
    ict = 0;

    for jam=0:23,					    %cycle thru 24 hourly stats files
        if jam<10,
            hr=['0' num2str(jam)];
        else
            hr=num2str(jam);
        end;                            %end if jam
        
%  met00828201_raw.txt
        e=[way_raw_data_flux, 'day', jd,'\kzr008' jd hr '_raw.txt'];
        %e=[way_raw_data, 'me1008' jd hr '_raw.txt'];

        disp(['Reading means from file  ',e]);
        flist=fopen(e,'r');

        if flist>0,					    %if the file exists,
            %10/08/2008 00:00 CR23X-CAMPBELL (SN: 3649)
            %0001001 176,2008,281,2359,9211.8,9217.2,9247.4,9269.2,2599,1.1806,3.8633,-.19454,-.16983,.00871,.00988,-99999,.03934,27.053,27.038,26.955,26.896,30.186,27.223,77.265,-31.53,-46.786,.98218,1.1356,-.02688,13.02,0,3.5335,1015,14.387,16.929,13.135,12.576,.33623,.00042,.00636,.01193,.0256,.00063,.00071,99999,.00004,.03949,.04647,.0359,.03427,.00306,.01698,.12719,1.9341,7.0526,.07072,.08206,.00015,.00241,0,.00177,.10647
            %mmss    Tb   SSv  Tv     RHv   ORGCv ORGSv SST  T     RH   ORG Flow
            %         1       2    3    4      5     6     7     8   9     10    11   12
            dmp=fgets(flist);		    %read header line
            YY = str2num(dmp(7:10));
            MM = str2num(dmp(1:2));
            DD = str2num(dmp(4:5));
            hh = str2num(dmp(12:13));
            % for p = 1:2  % short test read
            while feof(flist)==0,
                if backchk==0,
                    tzilch=jam;
                    backchk=1;
                end;						%end if
                clear st1 stz;
                if isfinite(flist),
                    dtmp = fgetl(flist);
                    data1 = dtmp(9:length(dtmp));
                    data2 = strrep(data1,'NAN','-99.');
                    C = textscan(data2,'%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f','Delimiter',',','CollectOutput',1);
                    %C = textscan(data2,'%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f','Delimiter',',','CollectOutput' ,'headerlines', 1,  'emptyvalue', NaN,'treatAsEmpty', 'Ship Motion');
                    %C = textscan(data2,'%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f','Delimiter',',' ,'emptyvalue', NaN);
                    tmp = C{:};
                    tim = dtmp(1:8);
                    mm = str2num(tim(:,1:2));
                    ss = str2num(tim(:,3:8))/1000;
                    %test for a bad line and skip
                    if isempty(tmp) || length(ss)>1
                        disp(data1) % print out bad line
                    elseif ~isempty(tmp) && length(ss)==1
                        ict = ict + 1;
                        stx(ict,:) = tmp(1,:);
                        %calculate year day
                        yd=datenum(YY,MM,DD,hh,0,0)-datenum(YY-1,12,31);
                        jdn(ict,1) = yd + (((mm+(ss/60))/60))/24;
                        %stx=fscanf(flist,'%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g',[77,1]);
                        %                          1                           2                          3                          4                         5
                        [nr1,nl1]=size(stx);
                        dmp4=fgets(flist);
                    end;                    %end if st0
                end
            end;                        %end while feof
            fclose(flist);
        end;                            %end if flist
    end;      %end for jam
    st2 = stx;
    jad = jdn;
    
    % 3 PIR R
    % 5 PIR V
    % 7 PSP V
    % 9 PIR W/m**2
    %11 PIR Temp C
    %13 PSP W/m**2
    %15 Bat VDC
    % calculation to convert LW to W/M2
    lw=(st2(:,5)/.00980)+(5.67*10^-8*((st2(:,11)+273.15)^4));
    
    %for jj = 1:15
        figure(1)
        plot(jad,lw,'k')
        title('PSD K-Z LW')
        ylabel('W/m**2')
        xlabel(' YearDay (UTC)')
        print('-djpeg90 ',[way_raw_images_flux '\KZ_LW_' num2str(ddd) '.jpg']);
        
        figure(2)
        plot(jad,st2(:,13),'k')
        title('PSD K-Z SW')
        ylabel('W/m**2')
        xlabel(' YearDay (UTC)')
        print('-djpeg90 ',[way_raw_images_flux '\KZ_SW_' num2str(ddd) '.jpg']);
        
        figure(3)
        plot(jad,st2(:,15),'k')
        title('PSD K-Z Bat')
        ylabel('VDC')
        xlabel(' YearDay (UTC)')
        print('-djpeg90 ',[way_raw_images_flux '\KZ_Bat_' num2str(ddd) '.jpg']);
        
        figure(4)
        plot(jad,st2(:,11),'k')
        title('PSD K-Z Temp')
        ylabel('C')
        xlabel(' YearDay (UTC)')
        print('-djpeg90 ',[way_raw_images_flux '\KZ_T_' num2str(ddd) '.jpg']);
    %end
end % day loop

st2(:,1)=jad; % replace all 7999s with yearday

if saveit
    flist=fopen([way_proc_data_flux 'kzr' jd '.txt'],'wt');
    fprintf(flist,'%12.8f %6i %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f %6.1f %8.3f %7.2f %10.6f %13.3e %13.3e %6.2f\n',st2');
    fclose('all');
    
%     [r,c] = size(st2);
%     st2(:,c+1) = jad;
%     kzr = st2;
%     save('way_raw_data_flux', 'kzr'); % save.mat to be used for comparisons
end;
