close all
clear all


hourly_data_file = '../HourlyResults/HourlyAverages.mat'

decoded_data_path = '../DecodedResults/';


data_file_nums = [100:100:5400 5483];

PC_Time = [];
PC_RPM =[];
PC_BattCurr = [];
PC_LoadCurr = [];
PC_Voltage = [];
PC_Status = [];
PC_WindingCurrent = [];
PC_TargVolt = [];
PC_TargCurr = [];

for i = 1:length(data_file_nums)
  filename = ['PowerData_' num2str(data_file_nums(i)) '.mat']
  data = load(filename);
  PC_Time = [PC_Time ; data.PC_Time];
  PC_RPM = [PC_RPM ; data.PC_RPM];
  PC_WindingCurrent = [PC_WindingCurrent ; data.PC_WindingCurrent];
  PC_BattCurr = [PC_BattCurr; data.PC_BattCurr];
  PC_LoadCurr = [PC_LoadCurr; data.PC_LoadCurr];
  PC_TargVolt = [PC_TargVolt ; data.PC_TargVolt];
  PC_TargCurr = [PC_TargCurr ; data.PC_TargCurr];
  PC_Voltage = [PC_Voltage; data.PC_Voltage];
  PC_Status = [PC_Status; data.PC_Status];
  disp(['Loaded ' num2str(i) ' of ' num2str(length(data_file_nums))]);
end 

Kv = 51;  %  Vrms/kRPM

PeakEMF = sqrt(2)*Kv*PC_RPM/1000;

Power = PC_Voltage.*(PC_LoadCurr+PC_BattCurr);

% Time Histograms
figure
bins = 0:100:6000;
ah1 = subplot(2,1,1)
h_RPM = histogram(abs(PC_RPM),bins);
xlabel('RPM');
title([num2str(length(PC_RPM)) ' observations between ' datestr(PC_Time(1)) ' and ' datestr(PC_Time(end))]);
grid on

bins = 0:5:400;
ah2 = subplot(2,1,2)
h_PeakEMF = histogram(abs(PeakEMF),bins);
xlabel('Peak EMF (V)');
title([num2str(length(PC_RPM)) ' observations between ' datestr(PC_Time(1)) ' and ' datestr(PC_Time(end))]);
grid on


% Power Distributions
for i = 1:length(h_RPM.BinEdges)-1
    idx = find((abs(PC_RPM) > h_RPM.BinEdges(i)) & (abs(PC_RPM) <= h_RPM.BinEdges(i+1)));
    disp(['Searched ' num2str(i) ' of ' num2str(length(h_RPM.BinEdges)) ' RPM bins']);
    Energy(i) = sum(.1*Power(idx));  %Joules
end

TotalEnergy = sum(Energy);

PercentTotalEnergy = Energy/TotalEnergy;

figure
subplot(2,1,1)
bar(h_RPM.BinEdges(1:end-1),PercentTotalEnergy)
xlabel('RPM');
ylabel('Percent of Total Energy Captured');

subplot(2,1,2)
plot(h_RPM.BinEdges(1:end-1),cumsum(PercentTotalEnergy));
xlabel('RPM');
ylabel('Cumulative Percent of Total Energy Captured');
grid on


clear Energy;
clear TotalEnergy;
clear PercentTotalEnergy;



% Power Distributions
for i = 1:length(h_PeakEMF.BinEdges)-1
    idx = find((abs(PeakEMF) > h_PeakEMF.BinEdges(i)) & (abs(PeakEMF) <= h_PeakEMF.BinEdges(i+1)));
    disp(['Searched ' num2str(i) ' of ' num2str(length(h_PeakEMF.BinEdges)) ' RPM bins']);
    Energy(i) = sum(.1*Power(idx));  %Joules
end

TotalEnergy = sum(Energy);

PercentTotalEnergy = Energy/TotalEnergy;

figure
subplot(2,1,1)
bar(h_PeakEMF.BinEdges(1:end-1),PercentTotalEnergy)
xlabel('Peak EMF');
ylabel('Percent of Total Energy Captured');

subplot(2,1,2)
plot(h_PeakEMF.BinEdges(1:end-1),cumsum(PercentTotalEnergy));
xlabel('Peak EMF');
ylabel('Cumulative Percent of Total Energy Captured');
grid on


