Improved logic for language detection