%% audit post-processing

% get audit vars
audit_vars = who('audit__*');
audit = [];

% Move individual variables into audit structure
for i = 1:length(audit_vars)
    
    if eval([ '~isempty(',  audit_vars{i}, ');'])
        % eval new var into struct replace double underscores with dots
        eval([strrep(audit_vars{i}, '__', '.') ' = ' audit_vars{i} ';']);
    end
end


if isempty( audit )
	clear audit
else
    % auto-calculate KE and tire loss energies and axle losses
    audit.energy_balance.system_KE_kJ = sum_workspace_vars(who('audit__mech*KE_kJ'));
    audit.energy_balance.brake_loss_kJ = sum_workspace_vars(who('audit__mech*brake_neg_kJ'));
    audit.energy_balance.rolling_resistance_loss_kJ = sum_workspace_vars(who('audit__mech*rolling_drag_neg_kJ'));
    audit.energy_balance.prop_axle_loss_kJ = sum_workspace_vars(who('audit__mech*final_drive__loss_kJ'));
	audit.energy_balance.tire_loss_kJ =	sum_workspace_vars(who('audit__mech*tire__input_pos_kJ')) - ...
										sum_workspace_vars(who('audit__mech*tire__output_pos_kJ')) + ...
										sum_workspace_vars(who('audit__mech*tire__output_neg_kJ')) - ...
										sum_workspace_vars(who('audit__mech*tire__input_neg_kJ'));
    if REVS.verbose > 0 
        audit.time = time;

        % Run Audit Calculations
        if  REVS.powertrain_type.is_conventional
            run_CVM_audit;
        elseif REVS.powertrain_type.is_bev
            run_EVM_audit;
        elseif REVS.powertrain_type.is_hybrid
            run_HVM_audit;
        end
    end

end

% cleanup
clear audit_vars;
clear audit__*;
clear i;
