+void destroy(struct file_with_size *node) {
+ struct file_with_size *next;
+ while(node) {
+ next = node->next;
+ free(node->filename);
+ free(node);
+ node = next;
+ }
+}
+
+/**********************************************************************/
+
+int compare_files(const void *x1, const void *x2) {
+ const struct file_with_size **f1, **f2;
+
+ f1 = (const struct file_with_size **) x1;
+ f2 = (const struct file_with_size **) x2;
+
+ if(reverse_sorting) {
+ if((*f1)->size < (*f2)->size) {
+ return 1;
+ } else if((*f1)->size > (*f2)->size) {
+ return -1;
+ } else {
+ return 0;
+ }
+ } else {
+ if((*f1)->size < (*f2)->size) {
+ return -1;
+ } else if((*f1)->size > (*f2)->size) {
+ return 1;
+ } else {
+ return 0;
+ }
+ }
+}
+
+void raw_print(char *buffer, char *filename, size_sum_t size) {
+ char *a, *b, *c, u;
+
+ b = buffer;
+ if(size) {
+ while(size) {
+ *(b++) = size%10 + '0';
+ size /= 10;
+ }
+ } else {
+ *(b++) = '0';
+ }
+
+ a = buffer;
+ c = b;
+ while(a < c) {
+ u = *a;
+ *(a++) = *(--c);
+ *c = u;
+ }
+
+ *(b++) = ' ';
+
+ sprintf(b, " %s\n", filename);
+}
+
+void fancy_print(char *buffer, char *filename, size_sum_t size) {
+ if(size < 1024) {
+ sprintf(buffer,
+ "% 7d %s\n",
+ ((int) size),
+ filename);
+ } else if(size < 1024 * 1024) {
+ sprintf(buffer,
+ "% 6.1fK %s\n",
+ ((double) (size))/(1024.0),
+ filename);
+ } else if(size < 1024 * 1024 * 1024) {
+ sprintf(buffer,
+ "% 6.1fM %s\n",
+ ((double) (size))/(1024.0 * 1024),
+ filename);
+ } else {
+ sprintf(buffer,
+ "% 6.1fG %s\n",
+ ((double) (size))/(1024.0 * 1024.0 * 1024.0),
+ filename);
+ }
+}
+
+void print_sorted(struct file_with_size *root, int width, int height) {
+ char line[BUFFER_SIZE];
+ struct file_with_size *node;
+ struct file_with_size **nodes;
+ int nb, n, first, last;
+
+ nb = 0;
+ for(node = root; node; node = node->next) {
+ nb++;
+ }
+
+ nodes = safe_malloc(nb * sizeof(struct file_with_size *));
+
+ n = 0;
+ for(node = root; node; node = node->next) {
+ nodes[n++] = node;
+ }
+
+ qsort(nodes, nb, sizeof(struct file_with_size *), compare_files);
+
+ first = 0;
+ last = nb;
+
+ if(forced_height) {
+ height = forced_height;
+ }
+
+ if(height > 0 && height < nb) {
+ first = nb - height;
+ }
+
+ if(show_top) {
+ n = last;
+ last = nb - first;
+ first = nb - n;
+ }
+
+ for(n = first; n < last; n++) {
+ if(fancy_size_display) {
+ fancy_print(line, nodes[n]->filename, nodes[n]->size);
+ } else {
+ raw_print(line, nodes[n]->filename, nodes[n]->size);
+ }
+ if(width >= 0 && width < BUFFER_SIZE) {
+ line[width] = '\0';
+ }
+ printf(line);
+ }
+
+ free(nodes);
+}
+
+/**********************************************************************/
+