Refactored a bit for better reuse in code