From 71e0803b1aa84d7c52145be1c177c5fac746d4a3 Mon Sep 17 00:00:00 2001
From: Allanis <allanis@saracraft.net>
Date: Mon, 5 Aug 2013 17:10:53 +0100
Subject: [PATCH] [Change] Order files with lfile_readDir by newest first.

---
 src/lfile.c | 63 ++++++++++++++++++++++++++++++++++++++++++++++++-----
 1 file changed, 57 insertions(+), 6 deletions(-)

diff --git a/src/lfile.c b/src/lfile.c
index e428fd9..4ab40c1 100644
--- a/src/lfile.c
+++ b/src/lfile.c
@@ -93,36 +93,87 @@ char** lfile_readDir(int* lfiles, const char* path) {
   snprintf(file, PATH_MAX, "%s%s", lfile_basePath(), path);
 
 #ifdef LINUX
+  int i, j, k, n;
   DIR* d;
   struct dirent *dir;
   char* name;
   int mfiles;
+  struct stat sb;
+  time_t* tt, *ft;
+  char** tfiles;
 
   (*lfiles) = 0;
   mfiles = 100;
-  files = malloc(sizeof(char*)*mfiles);
+  tfiles = malloc(sizeof(char*)*mfiles);
+  tt = malloc(sizeof(time_t)*mfiles);
 
   d = opendir(file);
-  if(d == NULL) {
+  if(d == NULL)
     return NULL;
-  }
 
+  /* Get the file list. */
   while((dir = readdir(d)) != NULL) {
     name = dir->d_name;
 
-    if((strcmp(name, ".")==0) || (strcmp(name, "..")==0))
+    /* Skip hidden directories. */
+    if(name[0] == '.')
       continue;
 
+    /* Stat the file. */
+    snprintf(file, PATH_MAX, "%s%s/%s", lfile_basePath(), path, name);
+    if(stat(file, &sb) == -1)
+      continue; /* Unable to stat. */
+
+    /* Enough memory? */
     if((*lfiles)+1 > mfiles) {
       mfiles += 100;
-      files = realloc(files, sizeof(char*) * mfiles);
+      tfiles = realloc(files, sizeof(char*) * mfiles);
+      tt = realloc(tt, sizeof(time_t) * mfiles);
     }
 
-    files[(*lfiles)] = strdup(name);
+    /* Write the information. */
+    tfiles[(*lfiles)] = strdup(name);
+    tt[(*lfiles)] = sb.st_mtime;
     (*lfiles)++;
   }
 
   closedir(d);
+
+  /* Sort by last changed date. */
+  if((*lfiles) > 0) {
+    /* Need to allocate some stuff. */
+    files = malloc(sizeof(char*)*(*lfiles));
+    ft = malloc(sizeof(time_t)*(*lfiles));
+
+    /* Fill the list. */
+    for(i = 0; i < (*lfiles); i++) {
+      n = -1;
+
+      /* Get the next lowest. */
+      for(j = 0; j < (*lfiles); j++) {
+        /* Is lower? */
+        if((n == -1) || (tt[j] > tt[n])) {
+          /* Check if it's already there. */
+          for(k = 0; k < i; k++)
+            if(strcmp(files[k], tfiles[j])==0)
+              break;
+
+          /* New lowest. */
+          if(k >= i)
+            n = j;
+        }
+      }
+      files[i] = tfiles[n];
+      ft[i] = tt[n];
+    }
+    free(ft);
+  } else
+    files = NULL;
+
+  /* Free temp stuff. */
+  free(tfiles);
+  free(tt);
+
 #else
 #error "Needs implementation."
 #endif