close all
clear all

base_path = getenv('BASE_PATH');
if(isempty(base_path))
  base_path = '../';
end
FTP_path = '/mbari/FTP/pub/Hamilton/LongTermPlots/';
DecodedFiles_path = [base_path 'DecodedResults/'];
WebSiteImagePath = [base_path 'images/'];
HourlyResults_path = [base_path 'HourlyResults/'];
HourlyAveragesFilename = 'HourlyAverages.mat';

LatAnchor = 36.7436;
LonAnchor = -121.8800;


files = dir([DecodedFiles_path '2*.mat']);

load([DecodedFiles_path files(end-1).name]);  %Load Most Recent Data, relies on files being arranged in chronological order.


x = SC_Range;
n = 10;
filtx = filter(ones(1,n)/n,1,x);
x = filtx;

Distance = 0;

height = 0.1;
row = 0;

datestr(Time_DateNum(end))


MostRecentBattVoltage = NaN; idx = find(~isnan(BC_Voltage)); if(~isempty(idx)) MostRecentBattVoltage = BC_Voltage(idx(end)); end
MostRecentLat = NaN; idx = find(~isnan(XB_Lat)); if(~isempty(idx)) MostRecentLat = XB_Lat(idx(end)); end
MostRecentLon = NaN; idx = find(~isnan(XB_Lon)); if(~isempty(idx)) MostRecentLon = XB_Lon(idx(end)); end
%DistanceLat = (MostRecentLat-LatAnchor)*60*1852;  %In meters
%DistanceLon = (MostRecentLon-LonAnchor)*60*1852*cos(LatAnchor*pi/180);  %In meters
%Distance = sqrt(DistanceLat.^2+DistanceLon.^2);

Distance = pos2dist(MostRecentLat,MostRecentLon,LatAnchor,LonAnchor,2)*1000;

if 0

figure('Visible','off')
axes('Visible','off');
text(0,1-row*height,'PowerBuoy Deployment Data','FontSize',14); row = row+1.1;
text(0,1-row*height,['   Most Recent Data = ' datestr(Time_DateNum(end)) ' GMT   (' datestr(Time_DateNum(end)-8/24,'HH:MM') ' PST)'],'FontSize',14); row = row+1;
text(0,1-row*height,['   Most Recent Location = ' num2str(MostRecentLat,5) 'N   ' num2str(abs(MostRecentLon),5) 'W    (' num2str(Distance,5) ' meters from anchor)'],'FontSize',14); row = row+1;
text(0,1-row*height,['   Battery Voltage = ' num2str(mean(MostRecentBattVoltage),3) ' Volts'],'FontSize',14); row = row+1;

disp('About to print');
print('-dpng',[WebSiteImagePath 'StatusTxt.png']);
disp('printed');


figure('Visible','off');
subplot(2,1,1)
plot((Time_DateNum-Time_DateNum(1))*(24*60),SC_Range)
xlabel('Minutes')
ylabel('Piston Position (in)')
subplot(2,1,2)
plot((Time_DateNum-Time_DateNum(1))*(24*60),BC_Voltage)
xlabel('Minutes')
ylabel('Battery Voltage')
print('-dpng',[WebSiteImagePath 'MostRecent_1.png']);

figure('Visible','off');
subplot(2,1,1)
plot((Time_DateNum-Time_DateNum(1))*(24*60),[PC_Power ; PC_Voltage.*PC_BattCurr ; PC_Voltage.*PC_LoadCurr])
xlabel('Minutes')
ylabel('Power (W)')
idx1 = find(~isnan(PC_Power));
idx2 = find(~isnan(PC_Voltage.*PC_BattCurr));
idx3 = find(~isnan(PC_Voltage.*PC_LoadCurr));
legend(['Total Power (mean = ' num2str(mean(PC_Power(idx1)))  ' W'],  ...
       ['Battery Power (mean = ' num2str(mean(PC_Voltage(idx2).*PC_BattCurr(idx2)))  ' W'],  ...
       ['Load Dump Power (mean = ' num2str(mean(PC_Voltage(idx3).*PC_LoadCurr(idx3)))  ' W']);

subplot(2,1,2)
plot((Time_DateNum-Time_DateNum(1))*(24*60),[BC_Voltage.*BC_Ips])
xlabel('Minutes')
ylabel('Controller Power (W)')

print('-dpng',[WebSiteImagePath 'MostRecent_2.png']);


N_VBalance =  bitand(uint16(BC_Status),31);  %Least significant 5 bits show number of balance lights on.
N_VStopCharge = bitand(bitshift(uint16(BC_Status),-5),31); %Next Least significant 5 bits show number of balance lights on.

figure('Visible','off');
subplot(2,1,1)
plot((Time_DateNum-Time_DateNum(1))*(24*60),[BC_GroundFault])
xlabel('Minutes')
ylabel('GroundFault Signal (mA)');

subplot(2,1,2)
plot((Time_DateNum-Time_DateNum(1))*(24*60),[N_VBalance ; N_VStopCharge])
xlabel('Minutes')
ylabel('Number of lights on');
legend('Balance Lights','Stop-Charge Lights');

print('-dpng',[WebSiteImagePath 'MostRecent_3.png']);


figure('Visible','off');
plot((Time_DateNum-Time_DateNum(1))*(24*60),PC_DiffPress)
xlabel('Minutes')
ylabel('Compensator Pressure (psi)');

print('-dpng',[WebSiteImagePath 'MostRecent_4.png']);




figure('Visible','off')
subplot(2,1,1)
plot((Time_DateNum-Time_DateNum(1))*(24*60),[SC_LowerPressure ; SC_UpperPressure])
xlabel('Minutes')
ylabel('Pressure (psia)')
idx1 = find(~isnan(SC_LowerPressure));
idx2 = find(~isnan(SC_UpperPressure));
legend(['Lower Spring Pressure  mean = ' num2str(mean(SC_LowerPressure(idx1))) ' psia'],['Upper Spring Pressure  mean = ' num2str(mean(SC_UpperPressure(idx2))) ' psia']);
subplot(2,1,2)
plot((Time_DateNum-Time_DateNum(1))*(24*60),BC_Hydrogen)
xlabel('Minutes')
ylabel('Hydrogen (% LEL)')
print('-dpng',[WebSiteImagePath 'MostRecent_5.png']);



figure('Visible','off')
subplot(2,1,1)
plot((Time_DateNum-Time_DateNum(1))*(24*60),[PC_Scale ; PC_Retract])
xlabel('Minutes')
ylabel('Scale/Retract Factor')
legend('Scale Factor','Retract Factor');
subplot(2,1,2)
plot((Time_DateNum-Time_DateNum(1))*(24*60),[PC_RPM ; PC_RPM_StdDev])
xlabel('Minutes')
ylabel('RPM')
legend('Instantaneous','Std Dev');


print('-dpng',[WebSiteImagePath 'MostRecent_6.png']);

end



%%%%%%%%%% Plot LAST 24 HOUR Data %%%%%%%%%%%%%%%%%%%%%%%

load([HourlyResults_path HourlyAveragesFilename]);


figure('Visible','off')
idx = find(HourlyData.Time_DateNum > HourlyData.Time_DateNum(end)-1);
%subplot(2,1,1)
plot(HourlyData.Time_DateNum(idx),HourlyData.BC_Voltage(idx))
title('Battery Voltage - Last 24 Hours');
ylabel('V');
datetick('x','mm/dd HH:MM');
%subplot(2,1,2)

print('-dpng',[WebSiteImagePath 'MeanBatteryVoltage_Last24Hrs.png']);


figure('Visible','off')
idx = find(HourlyData.Time_DateNum > HourlyData.Time_DateNum(end)-1);
subplot(3,1,1)
plot(HourlyData.Time_DateNum(idx),HourlyData.PC_Power(idx))
title('Hourly Power - Last 24 Hours');
ylabel('Hourly Mean (W)');
datetick('x','mm/dd HH:MM');
subplot(3,1,2)
plot(HourlyData.Time_DateNum(idx),HourlyData.PC_Power_max(idx));
ylabel('Hourly Max (W)');
datetick('x','mm/dd HH:MM');
subplot(3,1,3)
plot(HourlyData.Time_DateNum(idx),HourlyData.TC_DoorPosition(idx),'-o');
ylabel('Door Position (1 = closed)');
datetick('x','mm/dd HH:MM');

print('-dpng',[WebSiteImagePath 'MeanPowerPlot_Last24Hrs.png']);




figure('Visible','off')
idx = find(HourlyData.Time_DateNum > HourlyData.Time_DateNum(end)-1);
subplot(2,1,1)
%plot(HourlyData.Time_DateNum(idx),HourlyHydrogen_LEL(idx))
%ylabel('Hydrogen Level (%LEL)');
%datetick('x','mm/dd HH:MM');
subplot(2,1,2)
plot(HourlyData.Time_DateNum(idx),HourlyData.BC_GroundFault(idx));
ylabel('Ground Fault Signal (mA)');
datetick('x','mm/dd HH:MM');
print('-dpng',[WebSiteImagePath 'MeanH2AndGF_Last24Hrs.png']);


%%%%%%%%%%%% Plot ENTIRE DEPLOYMENT Data %%%%%%%%%%%%%%%%%%%%%%%%%%%

idx = find(HourlyData.Time_DateNum > datenum(2016,2,10));

figure('Visible','off')
%subplot(2,1,1)
plot(HourlyData.Time_DateNum(idx),HourlyData.BC_Voltage(idx))
datetick('x','mm/dd');
ylabel('Hourly Mean (V)');
title('Hourly Battery Voltage - Entire Deployment');
%subplot(2,1,2)

print('-dpng',[WebSiteImagePath 'MeanBatteryVoltagePlot.png']);



figure('Visible','off')
subplot(3,1,1)
plot(HourlyData.Time_DateNum(idx),HourlyData.PC_Power(idx))
datetick('x','mm/dd');
ylabel('Hourly Mean (W)');
title('Hourly Power - Entire Deployment');
subplot(3,1,2)
plot(HourlyData.Time_DateNum(idx),HourlyData.PC_Power_max(idx));
ylabel('Hourly Max (W)');
datetick('x','mm/dd');
subplot(3,1,3)
plot(HourlyData.Time_DateNum(idx),HourlyData.TC_DoorPosition(idx),'-o');
ylabel('Door Position (1 = closed)');
datetick('x','mm/dd HH:MM');

print('-dpng',[WebSiteImagePath 'MeanPowerPlot.png']);



figure('Visible','off')
subplot(3,1,1)
 plot(HourlyData.Time_DateNum(idx),HourlyData.SC_Range(idx));
 hold all
 plot(HourlyData.Time_DateNum(idx),HourlyData.SC_Range_max(idx));
 plot(HourlyData.Time_DateNum(idx),HourlyData.SC_Range_min(idx));
 legend('Mean','Max','Min','Location','NorthWest');
 ylabel('Piston Position (in)');
 datetick('x','mm/dd');
 title('Piston Position - Entire Deployment');
subplot(3,1,2)
 plot(HourlyData.Time_DateNum(idx),HourlyData.SC_OffSet(idx));
grid on;
 ylabel('Gas Spring Offset (in)');
 datetick('x','mm/dd');
subplot(3,1,3)
 plot(HourlyData.Time_DateNum(idx),HourlyData.SC_Slope(idx));
grid on;
 ylabel('Gas Spring Slope (in/psi)');
 datetick('x','mm/dd');


print('-dpng',[WebSiteImagePath 'MeanPistonPositionPlot.png']);



figure('Visible','off')
plot(HourlyData.Time_DateNum(idx),HourlyData.PC_DiffPress(idx));
ylabel('psi');
ylim([0 5]);
datetick('x','mm/dd');
grid on;
title('Compensator Pressure - Entire Deployment');
print('-dpng',[WebSiteImagePath 'MeanCompensatorPressurePlot.png']);



figure('Visible','off')
jdx = find(HourlyData.Time_DateNum(idx) > HourlyData.Time_DateNum(end)-1);
subplot(2,1,1)
plot(HourlyData.Time_DateNum(idx),HourlyData.BC_Hydrogen(idx))
ylabel('Hydrogen Level (%LEL)');
datetick('x','mm/dd HH:MM');
subplot(2,1,2)
plot(HourlyData.Time_DateNum(idx),HourlyData.BC_GroundFault(idx));
ylabel('Ground Fault Signal (mA)');
datetick('x','mm/dd HH:MM');
print('-dpng',[WebSiteImagePath 'MeanH2AndGF.png']);


cmd = ['cp ' WebSiteImagePath 'MeanCompensatorPressurePlot.png ' FTP_path '.'];
unix(cmd); 
cmd = ['cp ' WebSiteImagePath 'MeanPistonPositionPlot.png ' FTP_path '.'];
unix(cmd);
cmd = ['cp ' WebSiteImagePath 'MeanPowerPlot.png ' FTP_path '.'];
unix(cmd);
cmd = ['cp ' WebSiteImagePath 'MeanPowerPlot_Last24Hrs.png ' FTP_path '.'];
unix(cmd);
cmd = ['cp ' WebSiteImagePath 'MeanBatteryVoltagePlot.png ' FTP_path '.'];
unix(cmd);
cmd = ['cp ' WebSiteImagePath 'MeanBatteryVoltage_Last24Hrs.png ' FTP_path '.'];
unix(cmd);


exit  %End matlab after running (for use from command line)
