diff --git a/libavformat/img2.c b/libavformat/img2.c
index 77145cb..be51ad7 100644
--- a/libavformat/img2.c
+++ b/libavformat/img2.c
@@ -30,6 +30,9 @@
 #include "avio_internal.h"
 #include "internal.h"
 #include <strings.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include <dirent.h>
 
 typedef struct {
     const AVClass *class;  /**< Class for private options. */
@@ -133,27 +136,90 @@ static enum CodecID av_str2id(const IdStrMap *tags, const char *str)
     return CODEC_ID_NONE;
 }
 
+static void get_directory_from_path(const char* inPath, char* dirPath)
+{
+	int length, i;
+	length = strlen(inPath);
+
+	for(i=length-1;i>=0;i--)
+		if(inPath[i] == '\\' || inPath[i] =='/')
+			break;
+
+	if(i == -1) {
+		/* Files are in same directory as application */
+		snprintf(dirPath, MAX_PATH,"./");
+	} else {
+		av_strlcpy(dirPath, inPath, i + 1);
+		dirPath[i + 1] = '\0';
+	}
+}
+
+static int get_index_for_file(const char* path)
+{
+	int length, i, last_digit, first_digit, index;
+	length = strlen(path);
+
+	first_digit = -1;
+	last_digit = -1;
+
+	for(i=length-1;i>=0;i--) {
+		if(last_digit == -1) {
+			if(isdigit(path[i]))
+				last_digit = i;
+		} else {
+			if(isdigit(path[i]))
+				first_digit = i;
+			else
+				break;
+		}
+	}
+
+	index = -1;
+	if(first_digit != -1) {
+		sscanf(path + first_digit,"%d%*s",&index);
+	}
+
+	return index;
+}
+
 /* return -1 if no image found */
 static int find_image_range(int *pfirst_index, int *plast_index,
                             const char *path)
 {
     char buf[1024];
     int range, last_index, range1, first_index;
+    DIR *dp;
+	struct dirent *ep;
+	char dirPath[MAX_PATH];
 
     /* find the first image */
-    for(first_index = 0; first_index < 5; first_index++) {
-        if (av_get_frame_filename(buf, sizeof(buf), path, first_index) < 0){
-            *pfirst_index =
-            *plast_index = 1;
-            if (avio_check(buf, AVIO_FLAG_READ) > 0)
-                return 0;
-            return -1;
-        }
-        if (avio_check(buf, AVIO_FLAG_READ) > 0)
-            break;
-    }
-    if (first_index == 5)
-        goto fail;
+	first_index = -1;
+	get_directory_from_path(path, dirPath);
+
+	dp = opendir (dirPath);
+	if (dp != NULL) {
+		int min_index;
+		min_index = INT_MAX;
+		
+		while (ep = readdir (dp)) {
+			int file_index;
+			file_index = get_index_for_file(ep->d_name);
+			
+			if(file_index != -1) {
+				if(file_index < min_index)
+					min_index = file_index;
+			}
+		}
+
+		closedir(dp);
+
+		first_index = min_index;
+	}
+
+	if(first_index == -1) {
+		*pfirst_index = *plast_index = 1;
+		goto fail;
+	}
 
     /* find the last image */
     last_index = first_index;