%% BB3 software

%Directory
D = 'C:\BB3_TaraMed\BB3_leg09_Alger_Marseille\';

% open serial port
s = serial('COM6','BaudRate',19200,'DataBits',7);
fopen(s);
fid1 = s(1);
% set name for first text file
starttime = now;
fid2 = fopen([D 'BB3_' datestr(starttime,'yyyymmdd_HHMMSS') '.txt'],'wt');
% Preallocate
n = 0;
idx = 0;
red = nan(86400,1);
green = nan(86400,1);
blue = nan(86400,1);
plottime = nan(86400,1);
% infinite loop
while 1<2
% read a line of text from the port
tline = fscanf(fid1);
fprintf(tline)
% save the current time
time = now;
DateSt = datestr(time,'yyyymmdd_HHMMSS');
% start a new file every hour
if (time-starttime) > datenum(0,0,0,1,0,0)
    starttime = time;
    fclose(fid2)
    fid2 = fopen([D 'BB3_' DateSt '.txt'],'wt');
end
% plot every 10th point
n = n+1;
if n == 10
    idx = idx+1;
    C = textscan(tline,'%s%s%f%f%f%f%f%f%f');
    if idx == 1
        blue(idx) = C{4};
        green(idx) = C{6};
        red(idx) = C{8};
    else
    if abs(C{4}-blue(idx-1))<60 || isnan(blue(idx-1));
    blue(idx) = C{4};
    end
    if abs(C{6}-green(idx-1))<60 || isnan(green(idx-1));
    green(idx) = C{6};
    end
    if abs(C{8}-red(idx-1))<60 || isnan(red(idx-1));
    red(idx) = C{8};
    end
    end
    plottime(idx) = time;
    subplot(3,1,1)
    plot(gca,plottime,blue,'.-')
    datetick('keepticks');
    axis tight
    subplot(3,1,2)
    plot(gca,plottime,green,'.-g')
    datetick('keepticks');
    axis tight
    subplot(3,1,3)
    plot(gca,plottime,red,'.-r')
    datetick('keepticks');
    axis tight
    n = 0;
    drawnow
end
vect = datevec(time);
if vect(4) == 23 && vect(5) > 58
    close all
    idx = 0;
    red = nan(86400,1);
    green = nan(86400,1);
    blue = nan(86400,1);
    plottime = nan(86400,1);
end
% write the data line to file
fprintf(fid2,'%s',[DateSt ' ' tline]);
pause(1);
end

