added missing functions and extracted calculation logic into functions