function serialtrace_v1_1(realtime_buffer_size, archive_size, archive_prefix, signal_plot, bin_spec)

% serialtrace_v1_1.m
% 
% SYNTAX:       serialtrace_v1_1(realtime_buffer_size, archive_size, archive_prefix, signal_plot, bin_spec)
%               serialtrace_v1_1(30, 1440, 'SerialTest', 2, 1)
%
% INPUTS:       realtime_buffer_size    -   eg. 30 (minutes of data to retain in memory)
%               archive_size            -   eg. 1440 (minutes of data in each archive)
%               archive_prefix          -   eg. 'SerialTest' (archive prefix)
%               signal_plot             -   eg. 2 (select which signal to monitor)
%               bin_spec                -   eg. 1 (minutes per bin for summary stats)
%
% Interface with an instrument connected to COM1 to view/archive the
% incoming data stream.  RAW data are archived as both ASCII (.txt) files and
% Matlab (.mat) files. STATS data are archived as Matlab (.mat) files.
%
% ************************************************************************
% NB-1: When specifying directories for saving data make sure that none of
% the directory paths contain spaces.
%
% NB-2: Recorded timestamps reflect when each datapoint is read from the 
% input buffer and may differ slightly from when the data were actually
% collected (hockey-puck only).
% ************************************************************************
%
% Date Created:  March 20, 2004
% Date Modified: June 22, 2004
%
% Brandon Sackmann
% University of Maine
% School of Marine Sciences & 
% Ira C. Darling Marine Center
% 193 Clark's Cove Road
% Walpole, Maine 04573
%
% Tel: (207) 563-3146 x343
% Fax: (207) 563-3119
% Email: brandon.sackmann@maine.edu

% DECLARATIONS
global DIRECTORY_NAME_LOCAL
global DIRECTORY_NAME_ARCHIVE
global REALTIME_BUFFER_SIZE
global ARCHIVE_SIZE
global ARCHIVE_PREFIX
global SIGNAL_PLOT
global REALTIME_TIME
global REALTIME_SIGNAL
global ARCHIVE_TIME
global ARCHIVE_SIGNAL
global ARCHIVE_NUM
global ASCII_FID
global BIN_SPEC

% INITIALIZATIONS
DIRECTORY_NAME_LOCAL = uigetdir('C:\', 'Where should local data be saved...');
cd(DIRECTORY_NAME_LOCAL)
DIRECTORY_NAME_ARCHIVE = uigetdir('C:\', 'Where should archived data be saved...');
REALTIME_BUFFER_SIZE = floor(realtime_buffer_size);   % in minutes
ARCHIVE_SIZE = floor(archive_size);                   % in minutes
ARCHIVE_PREFIX = archive_prefix;
SIGNAL_PLOT = floor(signal_plot);
REALTIME_TIME = [];
REALTIME_SIGNAL = [];
ARCHIVE_TIME = [];
ARCHIVE_SIGNAL = [];
ARCHIVE_NUM = [];
ASCII_FID = [];
BIN_SPEC = floor(bin_spec);

% CREATE SERIAL PORT OBJECT
% ***MAY NEED TO BE CUSTOMIZED***
s1 = serial('COM1');
set(s1,'BaudRate',19200);  % eco-bb2f
%set(s1,'BaudRate',4800);  % hockey-puck
set(s1,'DataBits',8);
set(s1,'StopBits',1);
set(s1,'Parity','none');
set(s1,'InputBufferSize',32768);
set(s1,'ReadAsyncMode','continuous');

% ***************************
% BEGIN COMMUNICATION SESSION
% ***************************

% OPEN SERIAL PORT OBJECT
disp('Opening Serial Port - COM1')
fopen(s1);
fscanf(s1); % DISCARD INITIAL INCOMPLETE DATA POINT

% SERIALTRACE v1.1 GUI
guiHandles = serialtrace_v1_1_gui;

% START TIMERS
t1 = timer('TimerFcn',{@timedexec1,s1,guiHandles},'Period',1);
set(t1,'ExecutionMode','FixedSpacing')
start(t1)

t2 = timer('TimerFcn',{@timedexec2},'Period',REALTIME_BUFFER_SIZE*60,'StartDelay',REALTIME_BUFFER_SIZE*60);
set(t2,'ExecutionMode','FixedRate')
start(t2)


function timedexec1(obj,event,s1,guiHandles)

global DIRECTORY_NAME_LOCAL
global DIRECTORY_NAME_ARCHIVE
global REALTIME_BUFFER_SIZE
global ARCHIVE_SIZE
global ARCHIVE_PREFIX
global SIGNAL_PLOT
global REALTIME_TIME
global REALTIME_SIGNAL
global ARCHIVE_TIME
global ARCHIVE_SIGNAL
global ARCHIVE_NUM
global ASCII_FID
global BIN_SPEC

% MANAGE INCOMING DATA
while s1.BytesAvailable>=s1.InputBufferSize*0.01
    data = fscanf(s1);

    % PRINT DIAGNOSTICS
    disp([data(1:end-2) ' (Bytes Available: ' num2str(s1.BytesAvailable) '/' num2str(s1.InputBufferSize) ')'])          

    % PARSE SIGNAL FROM INSTRUMENT
    % ***MAY NEED TO BE CUSTOMIZED***
    [tstamp_date,tstamp_time,signal(1),signal(2),signal(3),signal(4),signal(5),signal(6)] = strread(data,'%s%s%f%f%f%f%f%f','delimiter','\t');  % eco-bb2f
    %[signal(1),signal(2),signal(3),signal(4),signal(5),signal(6)] = strread(data,'%f%f%f%f%f%f','delimiter',' ');  % hockey-puck
    tstamp = datenum([char(tstamp_date) ' ' char(tstamp_time)]);  % eco-bb2f
    %tstamp = now;  % hockey-puck
    
    if length(REALTIME_TIME)==0
        REALTIME_TIME = [tstamp];
        REALTIME_SIGNAL = [signal];
    elseif (tstamp-REALTIME_TIME(1))<(REALTIME_BUFFER_SIZE/60/24)
        REALTIME_TIME = [REALTIME_TIME; tstamp];
        REALTIME_SIGNAL = [REALTIME_SIGNAL; signal];
    elseif (tstamp-REALTIME_TIME(1))>=(REALTIME_BUFFER_SIZE/60/24)
        REALTIME_TIME(1:end) = [REALTIME_TIME(2:end); tstamp];
        REALTIME_SIGNAL(1:end,:) = [REALTIME_SIGNAL(2:end,:); signal];
    end
    
    if length(ARCHIVE_TIME)==0
        ARCHIVE_TIME = [tstamp];
        ARCHIVE_SIGNAL = [signal];
        
        % CREATE ARCHIVE_NUM
        time_vec = datevec(ARCHIVE_TIME(1));
        yr = num2str(time_vec(1));
        yd = num2str(floor(ARCHIVE_TIME(1)-datenum(['12/31/' num2str(time_vec(1)-1)])));
        hh = num2str(time_vec(4));
        if length(hh)==1
            hh = ['0' hh];
        end
        mm = num2str(time_vec(5));
        if length(mm)==1
            mm = ['0' mm];
        end
        ss = num2str(floor(time_vec(6)));
        if length(ss)==1
            ss = ['0' ss];
        end
        ARCHIVE_NUM = [yr yd hh mm ss];
        
        ASCII_FID = fopen([ARCHIVE_PREFIX '_' ARCHIVE_NUM '_RAW.txt'],'w');
        fprintf(ASCII_FID,'%s',[datestr(ARCHIVE_TIME(end)) '     ' data]); 
    elseif (tstamp-ARCHIVE_TIME(1))<(ARCHIVE_SIZE/60/24)
        ARCHIVE_TIME = [ARCHIVE_TIME; tstamp];
        ARCHIVE_SIGNAL = [ARCHIVE_SIGNAL; signal];
        fprintf(ASCII_FID,'%s',[datestr(ARCHIVE_TIME(end)) '     ' data]); 
    elseif (tstamp-ARCHIVE_TIME(1))>=(ARCHIVE_SIZE/60/24)
        fclose(ASCII_FID);
        eval(['save ' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_RAW.mat ARCHIVE_TIME ARCHIVE_SIGNAL']);
        system(['copy ' DIRECTORY_NAME_LOCAL '\' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_RAW.txt ' DIRECTORY_NAME_ARCHIVE '\' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_RAW.txt']);
        system(['copy ' DIRECTORY_NAME_LOCAL '\' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_RAW.mat ' DIRECTORY_NAME_ARCHIVE '\' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_RAW.mat']);
        timedexec2
        
        ARCHIVE_TIME = [tstamp];
        ARCHIVE_SIGNAL = [signal];
        
        % CREATE ARCHIVE_NUM
        time_vec = datevec(ARCHIVE_TIME(1));
        yr = num2str(time_vec(1));
        yd = num2str(floor(ARCHIVE_TIME(1)-datenum(['12/31/' num2str(time_vec(1)-1)])));
        hh = num2str(time_vec(4));
        if length(hh)==1
            hh = ['0' hh];
        end
        mm = num2str(time_vec(5));
        if length(mm)==1
            mm = ['0' mm];
        end
        ss = num2str(floor(time_vec(6)));
        if length(ss)==1
            ss = ['0' ss];
        end
        ARCHIVE_NUM = [yr yd hh mm ss];
        
        ASCII_FID = fopen([ARCHIVE_PREFIX '_' ARCHIVE_NUM '_RAW.txt'],'w');
        fprintf(ASCII_FID,'%s',[datestr(ARCHIVE_TIME(end)) '     ' data]); 
    end    
end

% SETUP AXIS LIMITS
if get(guiHandles.autoscale,'Value')
    set(guiHandles.realtimeymin,'String',num2str(min(REALTIME_SIGNAL(:,SIGNAL_PLOT))))
    set(guiHandles.realtimeymax,'String',num2str(max(REALTIME_SIGNAL(:,SIGNAL_PLOT))))
end
if get(guiHandles.definezoom,'Value')
    [zoomxcoords,zoomycoords] = ginput(2);
    set(guiHandles.zoomxmin,'String',datestr(zoomxcoords(1)))
    set(guiHandles.zoomxmax,'String',datestr(zoomxcoords(2)))
    set(guiHandles.zoomymin,'String',num2str(zoomycoords(2)))
    set(guiHandles.zoomymax,'String',num2str(zoomycoords(1)))
    set(guiHandles.definezoom,'Value',0)
end

realtime_axis = [datenum(get(guiHandles.realtimexmin,'String')) datenum(get(guiHandles.realtimexmax,'String'))...
                 str2num(get(guiHandles.realtimeymin,'String')) str2num(get(guiHandles.realtimeymax,'String'))];
zoom_axis     = [datenum(get(guiHandles.zoomxmin,'String')) datenum(get(guiHandles.zoomxmax,'String'))...
                 str2num(get(guiHandles.zoomymin,'String')) str2num(get(guiHandles.zoomymax,'String'))];
             
% ADJUST AXIS LIMITS IF NECESSARY - BASIC ERROR CHECKING
if REALTIME_TIME
    realtime_axis(1:2) = [(REALTIME_TIME(end)-(REALTIME_BUFFER_SIZE/60/24)) REALTIME_TIME(end)];
end
if zoom_axis(1)>=zoom_axis(2)
    zoom_axis(2) = zoom_axis(1)+(0.5/24);
    set(guiHandles.zoomxmax,'String',datestr(zoom_axis(2)))
elseif zoom_axis(3)>=zoom_axis(4)
    zoom_axis(4) = zoom_axis(3)+1;
    set(guiHandles.zoomymax,'String',num2str(zoom_axis(4)))
elseif realtime_axis(3)>=realtime_axis(4)
    realtime_axis(4) = realtime_axis(3)+1;
    set(guiHandles.realtimeymax,'String',num2str(realtime_axis(4)))
end

% PLOT AVAILABLE DATA
subplot(2,1,1)
set(gca,'Position',[0.07 0.57 0.6 0.35],'Fontsize',12)

axis(realtime_axis)
set(gca,'xtick',realtime_axis(1):(realtime_axis(2)-realtime_axis(1))/6:realtime_axis(2),...
        'xticklabel',{datestr(realtime_axis(1):(realtime_axis(2)-realtime_axis(1))/6:realtime_axis(2),'HH:MM')})
set(gca,'ytick',realtime_axis(3):(realtime_axis(4)-realtime_axis(3))/4:realtime_axis(4),...
        'yticklabel',{num2str([realtime_axis(3):(realtime_axis(4)-realtime_axis(3))/4:realtime_axis(4)]')})
set(gca,'xlim',[realtime_axis(1) realtime_axis(2)])
set(gca,'ylim',[realtime_axis(3) realtime_axis(4)])
hold on

if REALTIME_TIME
    plot(REALTIME_TIME,REALTIME_SIGNAL(:,SIGNAL_PLOT),'r'); hold on
    plot([zoom_axis(1) zoom_axis(2)],[zoom_axis(3) zoom_axis(3)],'b--'); hold on
    plot([zoom_axis(1) zoom_axis(2)],[zoom_axis(4) zoom_axis(4)],'b--'); hold on
    plot([zoom_axis(1) zoom_axis(1)],[zoom_axis(3) zoom_axis(4)],'b--'); hold on
    plot([zoom_axis(2) zoom_axis(2)],[zoom_axis(3) zoom_axis(4)],'b--'); hold off
end

h = title(['Real-Time View [Archive: ' ARCHIVE_PREFIX '\_' ARCHIVE_NUM '\_RAW]']);
set(h,'Fontsize',16)
h = ylabel(['Signal ' num2str(SIGNAL_PLOT)]);
set(h,'Fontsize',14)


subplot(2,1,2)
set(gca,'Position',[0.07 0.1 0.6 0.35],'Fontsize',12)

axis(zoom_axis)
set(gca,'xtick',zoom_axis(1):(zoom_axis(2)-zoom_axis(1))/6:zoom_axis(2),...
        'xticklabel',{datestr(zoom_axis(1):(zoom_axis(2)-zoom_axis(1))/6:zoom_axis(2),'HH:MM')})
set(gca,'ytick',zoom_axis(3):(zoom_axis(4)-zoom_axis(3))/4:zoom_axis(4),...
        'yticklabel',{num2str([zoom_axis(3):(zoom_axis(4)-zoom_axis(3))/4:zoom_axis(4)]')})
set(gca,'xlim',[zoom_axis(1) zoom_axis(2)])
set(gca,'ylim',[zoom_axis(3) zoom_axis(4)])
hold on

if REALTIME_TIME
    plot(REALTIME_TIME,REALTIME_SIGNAL(:,SIGNAL_PLOT),'r')
    h = title(['Zoom Window [Current Time: ' datestr(REALTIME_TIME(end)) ']']);
else
    h = title(['Zoom Window [Current Time: ]']);
end

set(h,'Fontsize',16)
h = ylabel(['Signal ' num2str(SIGNAL_PLOT)]);
set(h,'Fontsize',14)
h = xlabel('Time');
set(h,'Fontsize',14)

% CLOSE PROGRAM CLEANLY
if get(guiHandles.disconnect,'Value')
    % STOP TIMER
    stop(timerfind)
    delete(timerfind)
    
    % CLOSE SERIAL PORT OBJECT
    disp('Closing Serial Port - COM1')
    fclose(s1)
    delete(s1)
    clear s1 
    
    % COMPLETE PARTIAL ARCHIVES
    fclose(ASCII_FID);
    eval(['save ' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_RAW.mat ARCHIVE_TIME ARCHIVE_SIGNAL']);
    system(['copy ' DIRECTORY_NAME_LOCAL '\' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_RAW.txt ' DIRECTORY_NAME_ARCHIVE '\' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_RAW.txt']);
    system(['copy ' DIRECTORY_NAME_LOCAL '\' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_RAW.mat ' DIRECTORY_NAME_ARCHIVE '\' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_RAW.mat']);
    timedexec2
    
    % DISPLAY LOCATION OF SAVED DATA
    disp(['Local Save Location - ' DIRECTORY_NAME_LOCAL '\' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_RAW.mat'])
    disp(['Archive Save Location - ' DIRECTORY_NAME_ARCHIVE '\' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_RAW.mat'])
end

% ********************
% ********************

function timedexec2(obj,event)

global DIRECTORY_NAME_LOCAL
global DIRECTORY_NAME_ARCHIVE
global REALTIME_BUFFER_SIZE
global ARCHIVE_SIZE
global ARCHIVE_PREFIX
global SIGNAL_PLOT
global REALTIME_TIME
global REALTIME_SIGNAL
global ARCHIVE_TIME
global ARCHIVE_SIGNAL
global ARCHIVE_NUM
global ASCII_FID
global BIN_SPEC

% DETERMINE OF A STATISTICS FILE EXISTS - CREATE ONE IF NECESSARY
prev_file = dir([ARCHIVE_PREFIX '_' ARCHIVE_NUM '_STATS.mat']);
if length(prev_file)==0
    time_beg = ARCHIVE_TIME(1);
    time_end = ARCHIVE_TIME(end);    
    time_bin = time_beg:(BIN_SPEC/60/24):time_end;
    start_pos = 0;
else
    eval(['load ' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_STATS.mat']);
    time_beg = ARCHIVE_TIME_BIN(end);
    time_end = ARCHIVE_TIME(end);    
    time_bin = time_beg:(BIN_SPEC/60/24):time_end;
    start_pos = length(ARCHIVE_TIME_BIN)-1;
end
       
% CALCULATE STATISTICS - FOR EACH ARCHIVE
for i = 1:length(time_bin)
    if i<length(time_bin)
        dat_indices = find(ARCHIVE_TIME>=time_bin(i) & ARCHIVE_TIME<(time_bin(i+1)));
    else
        dat_indices = find(ARCHIVE_TIME>=time_bin(i) & ARCHIVE_TIME<(time_bin(i)+(BIN_SPEC/60/24)));
    end
    if dat_indices
        ARCHIVE_TIME_BIN(start_pos+i,1)     = time_bin(i);
        ARCHIVE_SIGNAL_MEAN(start_pos+i,:)  = mean(ARCHIVE_SIGNAL(dat_indices,:),1);
        ARCHIVE_SIGNAL_STD(start_pos+i,:)   = std(ARCHIVE_SIGNAL(dat_indices,:),0,1);
        ARCHIVE_SIGNAL_MED(start_pos+i,:)   = median(ARCHIVE_SIGNAL(dat_indices,:),1);
        if length(dat_indices)==1
            ARCHIVE_SIGNAL_16PER(start_pos+i,:) = median(ARCHIVE_SIGNAL(dat_indices,:),1);
            ARCHIVE_SIGNAL_84PER(start_pos+i,:) = median(ARCHIVE_SIGNAL(dat_indices,:),1);
        else
            ARCHIVE_SIGNAL_16PER(start_pos+i,:) = prctile(ARCHIVE_SIGNAL(dat_indices,:),16);
            ARCHIVE_SIGNAL_84PER(start_pos+i,:) = prctile(ARCHIVE_SIGNAL(dat_indices,:),84);
        end
        ARCHIVE_SIGNAL_MIN(start_pos+i,:)   = min(ARCHIVE_SIGNAL(dat_indices,:),[],1);
        ARCHIVE_SIGNAL_MAX(start_pos+i,:)   = max(ARCHIVE_SIGNAL(dat_indices,:),[],1);
        ARCHIVE_SIGNAL_N(start_pos+i,1)     = length(dat_indices);
    end
end
    
eval(['save ' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_STATS.mat ARCHIVE_TIME_* ARCHIVE_SIGNAL_*']);
system(['copy ' DIRECTORY_NAME_LOCAL '\' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_STATS.mat ' DIRECTORY_NAME_ARCHIVE '\' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_STATS.mat']);
    
% *****************************************
% GENERATE SUMMARY PLOTS - FOR EACH ARCHIVE
% ********MAY NEED TO BE CUSTOMIZED********
% *****************************************
figure(9999)
set(gcf,'PaperPosition',[0.25 0.25 8 10.5])

datebeg = ARCHIVE_TIME_BIN(1);
dateend = ARCHIVE_TIME_BIN(1)+(ARCHIVE_SIZE/60/24);
dateinterval = (dateend-datebeg)/4;

subplot(4,1,1)
xdat1 = ARCHIVE_TIME_BIN;
tmp = find(xdat1==0);
xdat1(tmp) = nan;
ydat1 = (ARCHIVE_SIGNAL_16PER(:,2)-52.833)*2.199E-05;
ydat2 = (ARCHIVE_SIGNAL_MED(:,2)-52.833)*2.199E-05;
ydat3 = (ARCHIVE_SIGNAL_84PER(:,2)-52.833)*2.199E-05;
h = plot(xdat1,ydat1,'g--',xdat1,ydat3,'r--');
set(h,'linewidth',1)
hold on;
h = plot(xdat1,ydat2,'b');
set(h,'linewidth',2)
legend('16th Percentile', '84th Percentile', 'Median',1)
axis tight
datetick('x')
h = gca;
set(h,'xtick',datebeg:dateinterval:dateend,'xticklabel',[],'fontsize',12)
set(h,'xlim',[datebeg dateend])
h = ylabel('\beta(117\circ, 470 nm) [m^-^1 sr^-^1]');
set(h,'fontsize',14)
h = title([ARCHIVE_PREFIX '\_' ARCHIVE_NUM '\_STATS']);
set(h,'fontsize',16)

subplot(4,1,2)
xdat1 = ARCHIVE_TIME_BIN;
tmp = find(xdat1==0);
xdat1(tmp) = nan;
ydat1 = (ARCHIVE_SIGNAL_16PER(:,4)-113.567)*1.161E-05;
ydat2 = (ARCHIVE_SIGNAL_MED(:,4)-113.567)*1.161E-05;
ydat3 = (ARCHIVE_SIGNAL_84PER(:,4)-113.567)*1.161E-05;
h = plot(xdat1,ydat1,'g--',xdat1,ydat3,'r--');
set(h,'linewidth',1)
hold on;
h = plot(xdat1,ydat2,'b');
set(h,'linewidth',2)
axis tight
datetick('x')
h = gca;
set(h,'xtick',datebeg:dateinterval:dateend,'xticklabel',[],'fontsize',12)
set(h,'xlim',[datebeg dateend])
h = ylabel('\beta(117\circ, 700 nm) [m^-^1 sr^-^1]');
set(h,'fontsize',14)

subplot(4,1,3)
xdat1 = ARCHIVE_TIME_BIN;
tmp = find(xdat1==0);
xdat1(tmp) = nan;
ydat1 = (ARCHIVE_SIGNAL_16PER(:,5)-55.6)*0.01713;
ydat2 = (ARCHIVE_SIGNAL_MED(:,5)-55.6)*0.01713;
ydat3 = (ARCHIVE_SIGNAL_84PER(:,5)-55.6)*0.01713;
h = semilogy(xdat1,ydat1,'g--',xdat1,ydat3,'r--');
set(h,'linewidth',1)
hold on;
h = semilogy(xdat1,ydat2,'b');
set(h,'linewidth',2)
axis tight
datetick('x')
h = gca;
set(h,'xtick',datebeg:dateinterval:dateend,'xticklabel',[],'fontsize',12)
set(h,'xlim',[datebeg dateend])
h = ylabel('Chlorophyll \it a \rm [mg m^-^3]');
set(h,'fontsize',14)

subplot(4,1,4)
xdat1 = ARCHIVE_TIME_BIN;
tmp = find(xdat1==0);
xdat1(tmp) = nan;
ydat3 = (ARCHIVE_SIGNAL_16PER(:,6)*-0.5979)+349.3;
ydat2 = (ARCHIVE_SIGNAL_MED(:,6)*-0.5979)+349.3;
ydat1 = (ARCHIVE_SIGNAL_84PER(:,6)*-0.5979)+349.3;
h = plot(xdat1,ydat1,'g--',xdat1,ydat3,'r--');
set(h,'linewidth',1)
hold on;
h = plot(xdat1,ydat2,'b');
set(h,'linewidth',2)
axis tight
datetick('x')
h = gca;
set(h,'xtick',datebeg:dateinterval:dateend,'xticklabel',{datestr(datebeg,'dd-mmm-yyyy') datestr(datebeg+dateinterval:dateinterval:dateend,'HH:MM')},'fontsize',12)
set(h,'xlim',[datebeg dateend])
h = ylabel('iTemperature [\circC]');
set(h,'fontsize',14)
h = xlabel('Time');
set(h,'fontsize',14)

print(gcf, '-dpng', [ARCHIVE_PREFIX '_' ARCHIVE_NUM '_STATS.png'])
system(['copy ' DIRECTORY_NAME_LOCAL '\' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_STATS.png ' DIRECTORY_NAME_ARCHIVE '\' ARCHIVE_PREFIX '_' ARCHIVE_NUM '_STATS.png']);
close(9999)

% *******************************************
% GENERATE SUMMARY DATA PLOTS - DAILY/MONTHLY
% *********MAY NEED TO BE CUSTOMIZED*********
% *******************************************
start_time(1) = ARCHIVE_TIME(end)-1;
end_time(1) = ARCHIVE_TIME(end);
start_time(2) = ARCHIVE_TIME(end)-30;
end_time(2) = ARCHIVE_TIME(end);
interval_description = {'DAILYSTATS', 'MONTHLYSTATS'};

statslist = dir('*_STATS.mat');
for i = 1:length(statslist)
    tmptimes(i,:) = statslist(i).name(end-22:end-10);
    tmpdate = datenum(['12/31/' num2str((str2num(tmptimes(i,1:4))-1))]);
    tmpdate = tmpdate+str2num(tmptimes(i,5:7));
    tmpdate = datestr(tmpdate);
    statstimes(i) = datenum([tmpdate ' ' tmptimes(i,8:9) ':' tmptimes(i,10:11) ':' tmptimes(i,12:13)]);
end

for i = 1:length(start_time)
    statsgood = find(statstimes>=start_time(i) & statstimes<end_time(i));
    statsfirst = min(statsgood-1);
    if statsfirst > 0
        statsgood = [statsfirst statsgood];
    end
    statslistgood = statslist(statsgood);

    ARCHIVE_TIME_BIN_COMP = [];
    ARCHIVE_SIGNAL_MEAN_COMP = [];
    ARCHIVE_SIGNAL_STD_COMP = [];
    ARCHIVE_SIGNAL_N_COMP = [];
    ARCHIVE_SIGNAL_MED_COMP = [];
    ARCHIVE_SIGNAL_16PER_COMP = [];
    ARCHIVE_SIGNAL_84PER_COMP = [];
    ARCHIVE_SIGNAL_MIN_COMP = [];
    ARCHIVE_SIGNAL_MAX_COMP = [];
    for j = 1:length(statslistgood)
        load(statslistgood(j).name)
        ARCHIVE_TIME_BIN_COMP = [ARCHIVE_TIME_BIN_COMP; ARCHIVE_TIME_BIN];
        ARCHIVE_SIGNAL_MEAN_COMP = [ARCHIVE_SIGNAL_MEAN_COMP; ARCHIVE_SIGNAL_MEAN];
        ARCHIVE_SIGNAL_STD_COMP = [ARCHIVE_SIGNAL_STD_COMP; ARCHIVE_SIGNAL_STD];
        ARCHIVE_SIGNAL_N_COMP = [ARCHIVE_SIGNAL_N_COMP; ARCHIVE_SIGNAL_N];
        ARCHIVE_SIGNAL_MED_COMP = [ARCHIVE_SIGNAL_MED_COMP; ARCHIVE_SIGNAL_MED];
        ARCHIVE_SIGNAL_16PER_COMP = [ARCHIVE_SIGNAL_16PER_COMP; ARCHIVE_SIGNAL_16PER];
        ARCHIVE_SIGNAL_84PER_COMP = [ARCHIVE_SIGNAL_84PER_COMP; ARCHIVE_SIGNAL_84PER];
        ARCHIVE_SIGNAL_MIN_COMP = [ARCHIVE_SIGNAL_MIN_COMP; ARCHIVE_SIGNAL_MIN];
        ARCHIVE_SIGNAL_MAX_COMP = [ARCHIVE_SIGNAL_MAX_COMP; ARCHIVE_SIGNAL_MAX];
    end
    gooddat = find(ARCHIVE_TIME_BIN_COMP>=start_time(i) & ARCHIVE_TIME_BIN_COMP<end_time(i));
    ARCHIVE_TIME_BIN_COMP = ARCHIVE_TIME_BIN_COMP(gooddat,:);
    ARCHIVE_SIGNAL_MEAN_COMP = ARCHIVE_SIGNAL_MEAN_COMP(gooddat,:);
    ARCHIVE_SIGNAL_STD_COMP = ARCHIVE_SIGNAL_STD_COMP(gooddat,:);
    ARCHIVE_SIGNAL_N_COMP = ARCHIVE_SIGNAL_N_COMP(gooddat,:);
    ARCHIVE_SIGNAL_MED_COMP = ARCHIVE_SIGNAL_MED_COMP(gooddat,:);
    ARCHIVE_SIGNAL_16PER_COMP = ARCHIVE_SIGNAL_16PER_COMP(gooddat,:);
    ARCHIVE_SIGNAL_84PER_COMP = ARCHIVE_SIGNAL_84PER_COMP(gooddat,:);
    ARCHIVE_SIGNAL_MIN_COMP = ARCHIVE_SIGNAL_MIN_COMP(gooddat,:);
    ARCHIVE_SIGNAL_MAX_COMP = ARCHIVE_SIGNAL_MAX_COMP(gooddat,:);
    eval(['save ' char(interval_description(i)) '.mat *COMP']);

    figure(9999)
    set(gcf,'PaperPosition',[0.25 0.25 8 10.5])

    datebeg = start_time(i);
    dateend = end_time(i);
    dateinterval = (dateend-datebeg)/4;

    subplot(4,1,1)
    xdat1 = ARCHIVE_TIME_BIN_COMP;
    tmp = find(xdat1==0);
    xdat1(tmp) = nan;
    ydat1 = (ARCHIVE_SIGNAL_16PER_COMP(:,2)-52.833)*2.199E-05;
    ydat2 = (ARCHIVE_SIGNAL_MED_COMP(:,2)-52.833)*2.199E-05;
    ydat3 = (ARCHIVE_SIGNAL_84PER_COMP(:,2)-52.833)*2.199E-05;
    h = plot(xdat1,ydat1,'g--',xdat1,ydat3,'r--');
    set(h,'linewidth',1)
    hold on;
    h = plot(xdat1,ydat2,'b');
    set(h,'linewidth',2)
    legend('16th Percentile', '84th Percentile', 'Median',1)
    axis tight
    datetick('x')
    h = gca;
    set(h,'xtick',datebeg:dateinterval:dateend,'xticklabel',[],'fontsize',12)
    set(h,'xlim',[datebeg dateend])
    h = ylabel('\beta(117\circ, 470 nm) [m^-^1 sr^-^1]');
    set(h,'fontsize',14)
    h = title([char(interval_description(i)) ' (Updated: ' datestr(max(ARCHIVE_TIME_BIN)) ')']);
    set(h,'fontsize',16)

    subplot(4,1,2)
    xdat1 = ARCHIVE_TIME_BIN_COMP;
    tmp = find(xdat1==0);
    xdat1(tmp) = nan;
    ydat1 = (ARCHIVE_SIGNAL_16PER_COMP(:,4)-113.567)*1.161E-05;
    ydat2 = (ARCHIVE_SIGNAL_MED_COMP(:,4)-113.567)*1.161E-05;
    ydat3 = (ARCHIVE_SIGNAL_84PER_COMP(:,4)-113.567)*1.161E-05;
    h = plot(xdat1,ydat1,'g--',xdat1,ydat3,'r--');
    set(h,'linewidth',1)
    hold on;
    h = plot(xdat1,ydat2,'b');
    set(h,'linewidth',2)
    axis tight
    datetick('x')
    h = gca;
    set(h,'xtick',datebeg:dateinterval:dateend,'xticklabel',[],'fontsize',12)
    set(h,'xlim',[datebeg dateend])
    h = ylabel('\beta(117\circ, 700 nm) [m^-^1 sr^-^1]');
    set(h,'fontsize',14)

    subplot(4,1,3)
    xdat1 = ARCHIVE_TIME_BIN_COMP;
    tmp = find(xdat1==0);
    xdat1(tmp) = nan;
    ydat1 = (ARCHIVE_SIGNAL_16PER_COMP(:,5)-55.6)*0.01713;
    ydat2 = (ARCHIVE_SIGNAL_MED_COMP(:,5)-55.6)*0.01713;
    ydat3 = (ARCHIVE_SIGNAL_84PER_COMP(:,5)-55.6)*0.01713;
    h = semilogy(xdat1,ydat1,'g--',xdat1,ydat3,'r--');
    set(h,'linewidth',1)
    hold on;
    h = semilogy(xdat1,ydat2,'b');
    set(h,'linewidth',2)
    axis tight
    datetick('x')
    h = gca;
    set(h,'xtick',datebeg:dateinterval:dateend,'xticklabel',[],'fontsize',12)
    set(h,'xlim',[datebeg dateend])
    h = ylabel('Chlorophyll \it a \rm [mg m^-^3]');
    set(h,'fontsize',14)
    
    subplot(4,1,4)
    xdat1 = ARCHIVE_TIME_BIN_COMP;
    tmp = find(xdat1==0);
    xdat1(tmp) = nan;
    ydat3 = (ARCHIVE_SIGNAL_16PER_COMP(:,6)*-0.5979)+349.3;
    ydat2 = (ARCHIVE_SIGNAL_MED_COMP(:,6)*-0.5979)+349.3;
    ydat1 = (ARCHIVE_SIGNAL_84PER_COMP(:,6)*-0.5979)+349.3;
    h = plot(xdat1,ydat1,'g--',xdat1,ydat3,'r--');
    set(h,'linewidth',1)
    hold on;
    h = plot(xdat1,ydat2,'b');
    set(h,'linewidth',2)
    axis tight
    datetick('x')
    h = gca;
    if i == 1
        set(h,'xtick',datebeg:dateinterval:dateend,'xticklabel',{datestr(datebeg,'dd-mmm-yyyy') datestr(datebeg+dateinterval:dateinterval:dateend,'HH:MM')},'fontsize',12)
    elseif i == 2
        set(h,'xtick',datebeg:dateinterval:dateend,'xticklabel',{datestr(datebeg:dateinterval:dateend,'dd-mmm-yyyy')},'fontsize',12)
    end
    set(h,'xlim',[datebeg dateend])
    h = ylabel('iTemperature [\circC]');
    set(h,'fontsize',14)
    h = xlabel('Time');
    set(h,'fontsize',14)

    print(gcf, '-dpng', [char(interval_description(i)) '.png'])
    close(9999)

    system(['copy ' DIRECTORY_NAME_LOCAL '\' char(interval_description(i)) '* ' DIRECTORY_NAME_ARCHIVE '\']);
end

% SYNCHRONIZE DATA DIRECTORIES IF NECESSARY - SUFFER THROUGH NETWORK OUTAGE
local_files = dir([DIRECTORY_NAME_LOCAL '\' ARCHIVE_PREFIX '*RAW.mat']);
archive_files = dir([DIRECTORY_NAME_ARCHIVE '\' ARCHIVE_PREFIX '*RAW.mat']);

if length(local_files)>0
	if length(archive_files)==0
        system(['copy ' DIRECTORY_NAME_LOCAL '\' ARCHIVE_PREFIX '* ' DIRECTORY_NAME_ARCHIVE '\']);
	else
        for i = 1:length(local_files)
            if i > length(archive_files)
                system(['copy ' DIRECTORY_NAME_LOCAL '\' local_files(i).name(1:end-8) '* ' DIRECTORY_NAME_ARCHIVE '\']);
                archive_files = dir([DIRECTORY_NAME_ARCHIVE '\' ARCHIVE_PREFIX '*RAW.mat']);
            elseif ~strcmp(local_files(i).name,archive_files(i).name)
                system(['copy ' DIRECTORY_NAME_LOCAL '\' local_files(i).name(1:end-8) '* ' DIRECTORY_NAME_ARCHIVE '\']);
                archive_files = dir([DIRECTORY_NAME_ARCHIVE '\' ARCHIVE_PREFIX '*RAW.mat']);
            end
        end
	end
end