diff --git a/pd/src/s_file.c b/pd/src/s_file.c
index 5f8f570e65fc88fdf7379053292c8a112f4c0b8c..63d575d12a6f0bc7099d8db641decf6964a51ad9 100644
--- a/pd/src/s_file.c
+++ b/pd/src/s_file.c
@@ -609,6 +609,14 @@ void sys_loadpreferences( void)
                 break;
             if (sscanf(prefbuf, "%d", &midiindev[i]) < 1)
                 break;
+            /* AG: If we have a name for the device, find the proper device
+               index in case that there was a change to the device list
+               between invocations. */
+            sprintf(keybuf, "midiindevname%d", i+1);
+            if (sys_getpreference(keybuf, prefbuf, MAXPDSTRING)) {
+              int d = sys_mididevnametonumber(0, prefbuf);
+              if (d >= 0) midiindev[i] = d;
+            }
             nmidiindev++;
         }
     }
@@ -630,6 +638,14 @@ void sys_loadpreferences( void)
                 break;
             if (sscanf(prefbuf, "%d", &midioutdev[i]) < 1)
                 break;
+            /* AG: If we have a name for the device, find the proper device
+               index in case that there was a change to the device list
+               between invocations. */
+            sprintf(keybuf, "midioutdevname%d", i+1);
+            if (sys_getpreference(keybuf, prefbuf, MAXPDSTRING)) {
+              int d = sys_mididevnametonumber(1, prefbuf);
+              if (d >= 0) midioutdev[i] = d;
+            }
             nmidioutdev++;
         }
     }
@@ -788,6 +804,14 @@ void glob_savepreferences(t_pd *dummy)
         sprintf(buf1, "midiindev%d", i+1);
         sprintf(buf2, "%d", midiindev[i]);
         sys_putpreference(buf1, buf2);
+        /* AG: If we have a name for the device, store it with the device
+           index, so that we can find the proper device index after a change
+           to the device list between invocations. */
+        sys_mididevnumbertoname(0, midiindev[i], buf2, MAXPDSTRING);
+        if (*buf2) {
+          sprintf(buf1, "midiindevname%d", i+1);
+          sys_putpreference(buf1, buf2);
+        }
     }
     sys_putpreference("nomidiout", (nmidioutdev <= 0 ? "True" : "False"));
     /* AG: nmidiout */
@@ -798,6 +822,14 @@ void glob_savepreferences(t_pd *dummy)
         sprintf(buf1, "midioutdev%d", i+1);
         sprintf(buf2, "%d", midioutdev[i]);
         sys_putpreference(buf1, buf2);
+        /* AG: If we have a name for the device, store it with the device
+           index, so that we can find the proper device index after a change
+           to the device list between invocations. */
+        sys_mididevnumbertoname(1, midioutdev[i], buf2, MAXPDSTRING);
+        if (*buf2) {
+          sprintf(buf1, "midioutdevname%d", i+1);
+          sys_putpreference(buf1, buf2);
+        }
     }
         /* file search path */