refactored the calculate_fg function to use less if statements for better performance