Magento: Fix 404 URL not found on language change in a multilanguage shop

diff -Naur /tmp/magento/app/code/core/Mage/Core/Model/Url/Rewrite.php /var/www/app/code/core/Mage/Core/Model/Url/Rewrite.php
--- /root/magento/app/code/core/Mage/Core/Model/Url/Rewrite.php	2010-02-20 01:48:33.000000000 +0100
+++ /var/www/app/code/core/Mage/Core/Model/Url/Rewrite.php	2012-11-27 18:28:06.000000000 +0100
@@ -83,6 +83,23 @@
         if (is_array($path)) {
             foreach ($path as $pathInfo) {
                 $this->load($pathInfo, 'request_path');
+
+                if (!$this->getId() && !isset($_GET['___from_store'])) {
+                    $db = Mage::getSingleton('core/resource')->getConnection('default_read');
+                    $result = $db->query('select store_id from core_url_rewrite WHERE request_path = "' . $pathInfo . '"');
+                    if ($result) {
+                        $storeIds = array();
+                        if($row = $result->fetch(PDO::FETCH_ASSOC)) {
+                            $storeId = $row['store_id'];
+                            $storeCode = Mage::app()->getStore($storeId)->getCode();
+
+                            header("HTTP/1.1 301 Moved Permanently");
+                            header("Location: http://" . $_SERVER['HTTP_HOST'] . "/" . $pathInfo . "?___store=" . $storeCode);
+                            exit();
+                        }
+                    }
+                }