No-op; fix GPL address and use the explicit-program-name version.
[dcpomatic.git] / src / lib / image_filename_sorter.cc
1 /*
2     Copyright (C) 2015-2016 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "raw_convert.h"
22 #include "image_filename_sorter.h"
23 #include <boost/filesystem.hpp>
24 #include <boost/foreach.hpp>
25 #include <iostream>
26
27 using std::list;
28
29 bool
30 ImageFilenameSorter::operator() (boost::filesystem::path a, boost::filesystem::path b)
31 {
32         std::list<int> na = extract_numbers (a);
33         std::list<int> nb = extract_numbers (b);
34         if (na.empty() || nb.empty()) {
35                 return a.string() < b.string();
36         }
37
38         if (na.size() != nb.size()) {
39                 /* Just use the first one */
40                 return na.front() < nb.front();
41         }
42
43         std::list<int>::const_iterator i = na.begin ();
44         std::list<int>::const_iterator j = nb.begin ();
45
46         while (i != na.end()) {
47                 if (*i != *j) {
48                         return *i < *j;
49                 }
50                 ++i;
51                 ++j;
52         }
53
54         /* All the same */
55         return false;
56
57 }
58
59 list<int>
60 ImageFilenameSorter::extract_numbers (boost::filesystem::path p)
61 {
62         p = p.leaf ();
63
64         std::list<std::string> numbers;
65
66         std::string current;
67         for (size_t i = 0; i < p.string().size(); ++i) {
68                 if (isdigit (p.string()[i])) {
69                         current += p.string()[i];
70                 } else {
71                         if (!current.empty ()) {
72                                 numbers.push_back (current);
73                                 current.clear ();
74                         }
75                 }
76         }
77
78         if (!current.empty ()) {
79                 numbers.push_back (current);
80         }
81
82         std::list<int> numbers_as_int;
83         BOOST_FOREACH (std::string i, numbers) {
84                 numbers_as_int.push_back (raw_convert<int> (i));
85         }
86
87         return numbers_as_int;
88 }