Refactored two almost identical methods into one to avoid code duplication.