function [ ftp ] = REVS_calc_ftp_result( result, varargin)
%REVS_calc_ftp_results 
%	Reads hot udds simulation results and generates approximate FTP
%   fuel economy. This is accomplished by applying an adjustment for 
%	the cold start phase.  The composite fuel economy is also calculated 
%	with the appropriate bag weightings

cold_correction = parse_varargs(varargin, 'cold_correction', 1.2, 'numeric',{'scalar'});
num_bags = parse_varargs(varargin, 'bags', 3, 'numeric',{'scalar','>=',3,'<=',4});

if isempty(strfind(result.cycle_name,'UDDS')) || length(result.phase_time_secs) ~= 2
	error('Input test was not a UDDS, unable to generate FTP results');
end

if num_bags == 3
	bag_idx = [1,2,1];
	bag_correct = [cold_correction, 1, 1];
	
elseif num_bags ==4
	bag_idx = [1,2,1,2];
	bag_correct = [cold_correction, 1, 1, 1];
else
	error('Bags must be either 3 or 4');
end
	

% Uncorrected fields
ftp.phase_time_secs =  result.phase_time_secs(bag_idx);
ftp.phase_distance_mi =  result.phase_distance_mi(bag_idx);
ftp.phase_avg_speed_mph = result.phase_avg_speed_mph(bag_idx);


% Apply Correction to fuel fields
ftp.phase_fuel_g = bag_correct .* result.phase_fuel_g(bag_idx);
ftp.phase_fuel_gallons = bag_correct .* result.phase_fuel_gallons(bag_idx);
ftp.phase_gCO2pmi = bag_correct .* result.phase_gCO2pmi(bag_idx);

% Compute Other Phase Results
ftp.phase_FE_mpg = ftp.phase_distance_mi ./ ftp.phase_fuel_gallons;

% Sum up 3 or 4 bag results
ftp.total_distance_mi = sum( ftp.phase_distance_mi);						% Distance of "2" bags
ftp.total_time_secs = sum( ftp.phase_time_secs );							% Time of "2" bags
ftp.total_avg_speed_mph = ftp.total_distance_mi ./ ( ftp.total_time_secs /3600); % average speed over "2" bags

ftp.total_fuel_g = sum( ftp.phase_fuel_g );
ftp.total_fuel_gallons = sum( ftp.phase_fuel_gallons);

% Compute Composite Results (2 bag equivalent)
ftp.gCO2pmi = sum(ftp.phase_distance_mi([1,2,3]) .* ftp.phase_gCO2pmi([1,2,3]) .* [0.43, 1.0, 0.57] ) ./ sum( ftp.phase_distance_mi([1,2] )) ;  
ftp.FE_mpg = sum( ftp.phase_distance_mi([1,2] ) ) ./ sum( ftp.phase_fuel_gallons([1,2,3]) .* [0.43, 1.0, 0.57]);

end

