Cleaned up implementation to have less code duplication