Cleaned up messy function