]> Creatis software - gdcm.git/blob - src/gdcmSerieHelper.cxx
Improve IsCoherent method
[gdcm.git] / src / gdcmSerieHelper.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmSerieHelper.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/10/27 09:14:15 $
7   Version:   $Revision: 1.33 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18
19 #include "gdcmSerieHelper.h"
20 #include "gdcmDirList.h"
21 #include "gdcmFile.h"
22 #include "gdcmDictEntry.h" // for TranslateToKey
23 #include "gdcmDebug.h"
24 #include "gdcmUtil.h"
25
26 #include <math.h>
27 #include <vector>
28 #include <map>
29 #include <algorithm>
30 #include <stdio.h>  //for sscanf
31
32 namespace gdcm 
33 {
34 //-----------------------------------------------------------------------------
35
36 //-----------------------------------------------------------------------------
37 // Constructor / Destructor
38 /**
39  * \brief   Constructor from a given SerieHelper
40  */
41 SerieHelper::SerieHelper()
42 {
43    ClearAll();
44    UserLessThanFunction = 0;
45    DirectOrder = true;
46 }
47
48 /**
49  * \brief   Canonical destructor.
50  */
51 SerieHelper::~SerieHelper()
52 {
53    ClearAll();
54 }
55
56 /**
57  * \brief  Preventively, clear everything at constructor time.
58  *         ( use it at destructor time.)
59  */
60 void SerieHelper::ClearAll()
61 {
62    // For all the 'Single SerieUID' Filesets that may already exist 
63    FileList *l = GetFirstSingleSerieUIDFileSet();
64    while (l)
65    { 
66       // For all the gdcm::File of a File set
67       for (gdcm::FileList::iterator it  = l->begin();
68                                     it != l->end(); 
69                                   ++it)
70       {
71          (*it)->Delete(); // remove each entry
72       }
73       l->clear();
74       delete l;     // remove the container
75       l = GetNextSingleSerieUIDFileSet();
76    }
77 }
78
79 //-----------------------------------------------------------------------------
80
81 //-----------------------------------------------------------------------------
82
83 // Public
84 /**
85  * \brief add a gdcm::File to the Fileset corresponding to its Serie UID
86  * @param   filename Name of the file to deal with
87  */
88 void SerieHelper::AddFileName(std::string const &filename)
89 {
90    // Create a DICOM file
91    File *header = File::New();
92    header->SetLoadMode(LoadMode);
93    header->SetFileName( filename ); 
94    header->Load();
95
96    if ( header->IsReadable() )
97    {
98       int allrules = 1;
99       // First step : the user defined a set of rules for the DICOM file
100       // he is looking for.
101       // Make sure the file corresponds to his set of rules:
102
103       std::string s;
104       for(SerieExRestrictions::iterator it2 = ExRestrictions.begin();
105           it2 != ExRestrictions.end();
106           ++it2)
107       {
108          const ExRule &r = *it2;
109          s = header->GetEntryString( r.group, r.elem );
110          if ( !Util::CompareDicomString(s, r.value.c_str(), r.op) )
111          {
112            // Argh ! This rule is unmatched; let's just quit
113
114            allrules = 0;
115            break;
116          }
117       }
118
119       if ( allrules ) // all rules are respected:
120       {
121          // Allright! we have a found a DICOM that matches the user expectation. 
122          // Let's add it!
123
124          // 0020 000e UI REL Series Instance UID
125          const std::string &uid = header->GetEntryString(0x0020, 0x000e);
126          // if uid == GDCM_UNFOUND then consistently we should find GDCM_UNFOUND
127          // no need here to do anything special
128
129
130          if ( SingleSerieUIDFileSetHT.count(uid) == 0 )
131          {
132             gdcmDebugMacro(" New Serie UID :[" << uid << "]");
133             // create a std::list in 'uid' position
134             SingleSerieUIDFileSetHT[uid] = new FileList;
135          }
136          // Current Serie UID and DICOM header seems to match; add the file:
137          SingleSerieUIDFileSetHT[uid]->push_back( header );
138       }
139       else
140       {
141          // at least one rule was unmatched we need to deallocate the file:
142          header->Delete();
143       }
144    }
145    else
146    {
147       gdcmWarningMacro("Could not read file: " << filename );
148       header->Delete();
149    }
150 }
151
152 /**
153  * \brief add a gdcm::File to the first (and supposed to be unique) file set
154  *        of the gdcm::SerieHelper.
155  * \warning : this method should be used by aware users only!
156  *           Passing a gdcm::File* has the same effect than passing a file name!
157  * \todo : decide which one is wrong (the method, or the commentary)!
158  *           the following comment doesn't match the method :-(
159  *            User is supposed to know the files he want to deal with
160  *           and consider them they belong to the same Serie
161  *           (even if their Serie UID is different)
162  *           user will probabely OrderFileList() this list (actually, ordering
163  *           user choosen gdm::File is the sole interest of this method)
164  *           Moreover, using vtkGdcmReader::SetCoherentFileList() will avoid
165  *           vtkGdcmReader parsing twice the same files. 
166  *           *no* coherence check is performed, but those specified
167  *           by SerieHelper::AddRestriction()
168  * @param   header gdcm::File* of the file to deal with
169  */
170 void SerieHelper::AddGdcmFile(File *header)
171 {
172       int allrules = 1;
173       // First step the user has defined a set of rules for the DICOM 
174       // he is looking for.
175       // make sure the file correspond to his set of rules:
176       for(SerieRestrictions::iterator it =  Restrictions.begin();
177                                       it != Restrictions.end();
178                                     ++it)
179       {
180          const Rule &r = *it;
181          const std::string s;// = header->GetEntryValue( r.first );
182          if ( !Util::DicomStringEqual(s, r.second.c_str()) )
183          {
184            // Argh ! This rule is unmatch let's just quit
185            allrules = 0;
186            break;
187          }
188       }
189       if ( allrules ) // all rules are respected:
190       {
191          // Allright ! we have a found a DICOM that match the user expectation. 
192          // Let's add it !
193
194          const std::string &uid = "0";
195          // Serie UID of the gdcm::File* may be different.
196          // User is supposed to know what he wants
197
198          if ( SingleSerieUIDFileSetHT.count(uid) == 0 )
199          {
200             gdcmDebugMacro(" New Serie UID :[" << uid << "]");
201             // create a std::list in 'uid' position
202             SingleSerieUIDFileSetHT[uid] = new FileList;
203          }
204          // Current Serie UID and DICOM header seems to match; add the file:
205          SingleSerieUIDFileSetHT[uid]->push_back( header );
206       }
207          // Even if a rule was unmatch we don't deallocate the gdcm::File:
208 }
209
210 /**
211  * \brief add a rules for restricting a DICOM file to be in the serie we are
212  * trying to find. For example you can select only the DICOM file from a
213  * directory which would have a particular EchoTime==4.0.
214  * This method is a user level, value is not required to be formatted as a DICOM
215  * string
216  * @param   group  Group number of the target tag.
217  * @param   elem Element number of the target tag.
218  * @param value value to be checked to exclude File
219  * @param op  operator we want to use to check
220  */
221 void SerieHelper::AddRestriction(uint16_t group, uint16_t elem, 
222                                  std::string const &value, int op)
223 {
224    ExRule r;
225    r.group = group;
226    r.elem  = elem;
227    r.value = value;
228    r.op    = op;
229    ExRestrictions.push_back( r ); 
230 }
231
232 #ifndef GDCM_LEGACY_REMOVE
233 void SerieHelper::AddRestriction(TagKey const &key, std::string const &value)
234 {
235    Rule r;
236    r.first = key;
237    r.second = value;
238    Restrictions.push_back( r ); 
239 }
240 #endif
241
242 /**
243  * \brief Sets the root Directory
244  * @param   dir Name of the directory to deal with
245  * @param recursive whether we want explore recursively the root Directory
246  */
247 void SerieHelper::SetDirectory(std::string const &dir, bool recursive)
248 {
249    DirList dirList(dir, recursive); // OS specific
250   
251    DirListType filenames_list = dirList.GetFilenames();
252    for( DirListType::const_iterator it = filenames_list.begin(); 
253         it != filenames_list.end(); ++it)
254    {
255       AddFileName( *it );
256    }
257 }
258
259 /**
260  * \brief Sorts the given Fileset
261  * \warning This could be implemented in a 'Strategy Pattern' approach
262  *          But as I don't know how to do it, I leave it this way
263  *          BTW, this is also a Strategy, I don't know this is 
264  *          the best approach :)
265  */
266 void SerieHelper::OrderFileList(FileList *fileSet)
267 {
268
269    if ( SerieHelper::UserLessThanFunction )
270    {
271       UserOrdering( fileSet );
272       return; 
273    }
274    else if ( ImagePositionPatientOrdering( fileSet ) )
275    {
276       return ;
277    }
278    else if ( ImageNumberOrdering(fileSet ) )
279    {
280       return ;
281    }
282    else  
283    {
284       FileNameOrdering(fileSet );
285    }
286 }
287
288 /**
289  * \brief Elementary coherence checking of the files with the same Serie UID
290  * Only sizes and pixel type are checked right now ...
291  */ 
292 bool SerieHelper::IsCoherent(FileList *fileSet)
293 {
294    if(fileSet->size() == 1)
295    return true;
296
297    FileList::const_iterator it = fileSet->begin();
298
299    int nX =               (*it)->GetXSize();
300    int nY =               (*it)->GetYSize();
301    int pixelSize =        (*it)->GetPixelSize();
302    bool signedPixelData = (*it)->IsSignedPixelData();
303    it ++;
304    for ( ;
305          it != fileSet->end();
306        ++it)
307    {
308       if ( (*it)->GetXSize() != nX )
309          return false;
310       if ( (*it)->GetYSize() != nY )
311          return false;
312       if ( (*it)->GetPixelSize() != pixelSize )
313          return false;
314       if ( (*it)->IsSignedPixelData() != signedPixelData )
315          return false;
316       // probabely more is to be checked (?)      
317    }
318    return true;
319 }
320
321 #ifndef GDCM_LEGACY_REMOVE
322
323 FileList *SerieHelper::GetFirstCoherentFileList()
324 {
325    ItFileSetHt = SingleSerieUIDFileSetHT.begin();
326    if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
327       return ItFileSetHt->second;
328    return NULL;
329 }
330
331
332 FileList *SerieHelper::GetNextCoherentFileList()
333 {
334    gdcmAssertMacro (ItFileSetHt != SingleSerieUIDFileSetHT.end());
335   
336    ++ItFileSetHt;
337    if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
338       return ItFileSetHt->second;
339    return NULL;
340 }
341
342
343 FileList *SerieHelper::GetCoherentFileList(std::string SerieUID)
344 {
345    if ( SingleSerieUIDFileSetHT.count(SerieUID) == 0 )
346       return 0;     
347    return SingleSerieUIDFileSetHT[SerieUID];
348 }
349 #endif
350
351
352 /**
353  * \brief   Get the first Fileset while visiting the SingleSerieUIDFileSetmap
354  * @return  The first FileList (SingleSerieUIDFileSet) if found, otherwhise 0
355  */
356 FileList *SerieHelper::GetFirstSingleSerieUIDFileSet()
357 {
358    ItFileSetHt = SingleSerieUIDFileSetHT.begin();
359    if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
360       return ItFileSetHt->second;
361    return NULL;
362 }
363
364 /**
365  * \brief   Get the next Fileset while visiting the SingleSerieUIDFileSetmap
366  * \note : meaningfull only if GetNextSingleSerieUIDFileSet() already called 
367  * @return  The next FileList (SingleSerieUIDFileSet) if found, otherwhise 0
368  */
369 FileList *SerieHelper::GetNextSingleSerieUIDFileSet()
370 {
371    gdcmAssertMacro (ItFileSetHt != SingleSerieUIDFileSetHT.end());
372   
373    ++ItFileSetHt;
374    if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
375       return ItFileSetHt->second;
376    return NULL;
377 }
378
379 /**
380  * \brief   Get the SingleSerieUIDFileSet according to its Serie UID
381  * @param SerieUID SerieUID to retrieve
382  * \return pointer to the FileList (SingleSerieUIDFileSet) if found, otherwhise 0
383  */
384 FileList *SerieHelper::GetSingleSerieUIDFileSet(std::string SerieUID)
385 {
386    if ( SingleSerieUIDFileSetHT.count(SerieUID) == 0 )
387       return 0;     
388    return SingleSerieUIDFileSetHT[SerieUID];
389 }
390
391 /**
392  * \brief   Splits a Single SerieUID Fileset according to the Orientations
393  * @param fileSet File Set to be splitted
394  * \return  std::map of 'Xcoherent' File sets
395  */
396
397 XCoherentFileSetmap SerieHelper::SplitOnOrientation(FileList *fileSet)
398 {
399    XCoherentFileSetmap CoherentFileSet;
400
401    int nb = fileSet->size();
402    if (nb == 0 )
403       return CoherentFileSet;
404    float iop[6];
405
406    std::string strOrient;
407    std::ostringstream ossOrient;   
408    FileList::const_iterator it = fileSet->begin();
409    it ++;
410    for ( ;
411          it != fileSet->end();
412        ++it)
413    {     
414       // Information is in :      
415       // 0020 0037 : Image Orientation (Patient) or
416       // 0020 0035 : Image Orientation (RET)
417
418       // Let's build again the 'cosines' string, to be sure of it's format      
419       (*it)->GetImageOrientationPatient(iop);
420
421       ossOrient << iop[0];      
422       for (int i = 1; i < 6; i++)
423       {
424         ossOrient << "\\";
425         ossOrient << iop[i]; 
426       }      
427       strOrient = ossOrient.str();
428       ossOrient.str("");
429       // FIXME : is it a 'cleaner' way to initialize an ostringstream? 
430
431       if ( CoherentFileSet.count(strOrient) == 0 )
432       {
433          gdcmDebugMacro(" New Orientation :[" << strOrient << "]");
434          // create a File set in 'orientation' position
435          CoherentFileSet[strOrient] = new FileList;
436       }
437       // Current Orientation and DICOM header match; add the file:
438       CoherentFileSet[strOrient]->push_back( (*it) );
439    } 
440    return CoherentFileSet;
441 }
442
443 /**
444  * \brief   Splits a 'Single SerieUID' Fileset according to the Positions
445  * @param fileSet File Set to be splitted
446  * \return  std::map of 'Xcoherent' File sets
447  */
448
449 XCoherentFileSetmap SerieHelper::SplitOnPosition(FileList *fileSet)
450 {
451    XCoherentFileSetmap CoherentFileSet;
452
453    int nb = fileSet->size();
454    if (nb == 0 )
455       return CoherentFileSet;
456    float pos[3];
457    std::string strImPos;  // read on disc
458    std::ostringstream ossPosition;
459    std::string strPosition; // re computed
460    FileList::const_iterator it = fileSet->begin();
461    it ++;
462    for ( ;
463          it != fileSet->end();
464        ++it)
465    {     
466       // Information is in :      
467       // 0020,0032 : Image Position Patient
468       // 0020,0030 : Image Position (RET)
469
470       strImPos = (*it)->GetEntryString(0x0020,0x0032);
471       if ( strImPos == GDCM_UNFOUND)
472       {
473          gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
474          strImPos = (*it)->GetEntryString(0x0020,0x0030); // For ACR-NEMA images
475          if ( strImPos == GDCM_UNFOUND )
476          {
477             gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
478             // User wants to split on the 'Position'
479             // No 'Position' info found.
480             // We return an empty Htable !
481             return CoherentFileSet;
482          }  
483       }
484
485       if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", 
486                                               &pos[0], &pos[1], &pos[2]) != 3 )
487       {
488             gdcmWarningMacro( "Wrong number for Position : ["
489                        << strImPos << "]" );
490              return CoherentFileSet;
491       }
492
493       // Let's build again the 'position' string, to be sure of it's format      
494
495       ossPosition << pos[0];      
496       for (int i = 1; i < 3; i++)
497       {
498         ossPosition << "\\";
499         ossPosition << pos[i]; 
500       }      
501       strPosition = ossPosition.str();
502       ossPosition.str("");
503             
504       if ( CoherentFileSet.count(strPosition) == 0 )
505       {
506          gdcmDebugMacro(" New Position :[" << strPosition << "]");
507          // create a File set in 'position' position
508          CoherentFileSet[strPosition] = new FileList;
509       }
510       // Current Position and DICOM header match; add the file:
511       CoherentFileSet[strPosition]->push_back( (*it) );
512    }   
513    return CoherentFileSet;
514 }
515
516 /**
517  * \brief   Splits a 'Single SerieUID' File set Coherent according to the
518  *          value of a given Tag
519  * @param fileSet File Set to be splitted
520  * @param   group  group number of the target Element
521  * @param   elem element number of the target Element
522  * \return  std::map of 'Xcoherent' File sets
523  */
524
525 XCoherentFileSetmap SerieHelper::SplitOnTagValue(FileList *fileSet, 
526                                                uint16_t group, uint16_t elem)
527 {
528    XCoherentFileSetmap CoherentFileSet;
529
530    int nb = fileSet->size();
531    if (nb == 0 )
532       return CoherentFileSet;
533
534    std::string strTagValue;  // read on disc
535
536    FileList::const_iterator it = fileSet->begin();
537    it ++;
538    for ( ;
539          it != fileSet->end();
540        ++it)
541    {     
542       // Information is in :      
543       // 0020,0032 : Image Position Patient
544       // 0020,0030 : Image Position (RET)
545
546       strTagValue = (*it)->GetEntryString(group,elem);
547       
548       if ( CoherentFileSet.count(strTagValue) == 0 )
549       {
550          gdcmDebugMacro(" New Tag Value :[" << strTagValue << "]");
551          // create a File set in 'position' position
552          CoherentFileSet[strTagValue] = new FileList;
553       }
554       // Current Tag value and DICOM header match; add the file:
555       CoherentFileSet[strTagValue]->push_back( (*it) );
556    }
557    return CoherentFileSet;
558 }
559
560 //-----------------------------------------------------------------------------
561 // Protected
562
563 //-----------------------------------------------------------------------------
564 // Private
565 /**
566  * \brief sorts the images, according to their Patient Position
567  *  We may order, considering :
568  *   -# Image Position Patient
569  *   -# Image Number
570  *   -# File Name
571  *   -# More to come :-)
572  * \note : FileList = std::vector<File* >
573  * @param fileList Coherent File list (same Serie UID) to sort
574  * @return false only if the header is bugged !
575  */
576 bool SerieHelper::ImagePositionPatientOrdering( FileList *fileList )
577 //based on Jolinda Smith's algorithm
578 {
579    //iop is calculated based on the file file
580    float cosines[6];
581    float normal[3];
582    float ipp[3];
583    float dist;
584    float min = 0, max = 0;
585    bool first = true;
586    int n=0;
587    std::vector<float> distlist;
588
589    //!\todo rewrite this for loop.
590    for ( FileList::const_iterator 
591          it = fileList->begin();
592          it != fileList->end(); ++it )
593    {
594       if ( first ) 
595       {
596          (*it)->GetImageOrientationPatient( cosines );
597       
598          // You only have to do this once for all slices in the volume. Next, 
599          // for each slice, calculate the distance along the slice normal 
600          // using the IPP ("Image Position Patient") tag.
601          // ("dist" is initialized to zero before reading the first slice) :
602          normal[0] = cosines[1]*cosines[5] - cosines[2]*cosines[4];
603          normal[1] = cosines[2]*cosines[3] - cosines[0]*cosines[5];
604          normal[2] = cosines[0]*cosines[4] - cosines[1]*cosines[3];
605   
606          ipp[0] = (*it)->GetXOrigin();
607          ipp[1] = (*it)->GetYOrigin();
608          ipp[2] = (*it)->GetZOrigin();
609
610          dist = 0;
611          for ( int i = 0; i < 3; ++i )
612          {
613             dist += normal[i]*ipp[i];
614          }
615     
616          distlist.push_back( dist );
617
618          max = min = dist;
619          first = false;
620       }
621       else 
622       {
623          ipp[0] = (*it)->GetXOrigin();
624          ipp[1] = (*it)->GetYOrigin();
625          ipp[2] = (*it)->GetZOrigin();
626   
627          dist = 0;
628          for ( int i = 0; i < 3; ++i )
629          {
630             dist += normal[i]*ipp[i];
631          }
632
633          distlist.push_back( dist );
634
635          min = (min < dist) ? min : dist;
636          max = (max > dist) ? max : dist;
637       }
638       ++n;
639    }
640
641    // Then I order the slices according to the value "dist". Finally, once
642    // I've read in all the slices, I calculate the z-spacing as the difference
643    // between the "dist" values for the first two slices.
644    FileVector CoherentFileVector(n);
645    // CoherentFileVector.reserve( n );
646    CoherentFileVector.resize( n );
647    // gdcmAssertMacro( CoherentFileVector.capacity() >= n );
648
649    // Find out if min/max are coherent
650    if ( min == max )
651    {
652      gdcmWarningMacro("Looks like all images have the exact same image position"
653                       << ". No PositionPatientOrdering sort performed" );
654      return false;
655    }
656
657    float step = (max - min)/(n - 1);
658    int pos;
659    n = 0;
660     
661    //VC++ don't understand what scope is !! it -> it2
662    for (FileList::const_iterator it2  = fileList->begin();
663         it2 != fileList->end(); ++it2, ++n)
664    {
665       //2*n sort algo !!
666       //Assumption: all files are present (no one missing)
667       pos = (int)( fabs( (distlist[n]-min)/step) + .5 );
668
669       // a Dicom 'Serie' may contain scout views
670       // and images may have differents directions
671       // -> More than one may have the same 'pos'
672       // Sorting has then NO meaning !
673       if (CoherentFileVector[pos]==NULL)
674          CoherentFileVector[pos] = *it2;
675       else
676       {
677          gdcmWarningMacro( "At least 2 files with same position."
678                         << " No PositionPatientOrdering sort performed");
679          return false;
680       }
681    }
682
683    fileList->clear();  // doesn't delete list elements, only nodes
684
685    if (DirectOrder)
686    {  
687       //VC++ don't understand what scope is !! it -> it3
688       for (FileVector::const_iterator it3  = CoherentFileVector.begin();
689            it3 != CoherentFileVector.end(); ++it3)
690       {
691          fileList->push_back( *it3 );
692       }
693    }
694    else // user asked for reverse order
695    {
696       FileVector::const_iterator it4;
697       it4 = CoherentFileVector.end();
698       do
699       {
700          it4--;
701          fileList->push_back( *it4 );
702       } while (it4 != CoherentFileVector.begin() );
703    } 
704
705    distlist.clear();
706    CoherentFileVector.clear();
707
708    return true;
709 }
710
711 bool SerieHelper::ImageNumberLessThan(File *file1, File *file2)
712 {
713   return file1->GetImageNumber() < file2->GetImageNumber();
714 }
715
716 bool SerieHelper::ImageNumberGreaterThan(File *file1, File *file2)
717 {
718   return file1->GetImageNumber() > file2->GetImageNumber();
719 }
720
721 /**
722  * \brief sorts the images, according to their Image Number
723  * \note Works only on bona fide files  (i.e image number is a character string
724  *                                      corresponding to an integer)
725  *             within a bona fide serie (i.e image numbers are consecutive)
726  * @param fileList  File set (same Serie UID) to sort 
727  * @return false if non bona fide stuff encountered
728  */
729 bool SerieHelper::ImageNumberOrdering(FileList *fileList) 
730 {
731    int min, max, pos;
732    int n = fileList->size();
733
734    FileList::const_iterator it = fileList->begin();
735    min = max = (*it)->GetImageNumber();
736
737    for (; it != fileList->end(); ++it, ++n)
738    {
739       pos = (*it)->GetImageNumber();
740       min = (min < pos) ? min : pos;
741       max = (max > pos) ? max : pos;
742    }
743
744    // Find out if image numbers are coherent (consecutive)
745    if ( min == max || max == 0 || max >= (n+min) )
746    {
747       gdcmWarningMacro( " 'Image numbers' not coherent. "
748                         << " No ImageNumberOrdering sort performed.");
749       return false;
750    }
751    if (DirectOrder) 
752       std::sort(fileList->begin(), fileList->end(), 
753                                           SerieHelper::ImageNumberLessThan );
754    else
755       std::sort(fileList->begin(), fileList->end(),
756                                           SerieHelper::ImageNumberGreaterThan );
757
758    return true;
759 }
760
761 bool SerieHelper::FileNameLessThan(File *file1, File *file2)
762 {
763    return file1->GetFileName() < file2->GetFileName();
764 }
765
766 bool SerieHelper::FileNameGreaterThan(File *file1, File *file2)
767 {
768    return file1->GetFileName() > file2->GetFileName();
769 }
770 /**
771  * \brief sorts the images, according to their File Name
772  * @param fileList Coherent File list (same Serie UID) to sort
773  * @return false only if the header is bugged !
774  */
775 bool SerieHelper::FileNameOrdering(FileList *fileList)
776 {
777    if (DirectOrder) 
778       std::sort(fileList->begin(), fileList->end(), 
779                                        SerieHelper::FileNameLessThan);
780    else
781       std::sort(fileList->begin(), fileList->end(), 
782                                        SerieHelper::FileNameGreaterThan);
783
784    return true;
785 }
786
787 /**
788  * \brief sorts the images, according to user supplied function
789  * @param fileList Coherent File list (same Serie UID) to sort
790  * @return false only if the header is bugged !
791  */
792 bool SerieHelper::UserOrdering(FileList *fileList)
793 {
794    std::sort(fileList->begin(), fileList->end(), 
795                                     SerieHelper::UserLessThanFunction);
796    if (!DirectOrder) 
797    {
798       std::reverse(fileList->begin(), fileList->end());
799    }
800    return true;
801 }
802
803 //-----------------------------------------------------------------------------
804 // Print
805 /**
806  * \brief   Canonical printer.
807  */
808 void SerieHelper::Print(std::ostream &os, std::string const &indent)
809 {
810    // For all the Coherent File lists of the gdcm::Serie
811    SingleSerieUIDFileSetmap::iterator itl = SingleSerieUIDFileSetHT.begin();
812    if ( itl == SingleSerieUIDFileSetHT.end() )
813    {
814       gdcmWarningMacro( "No SingleSerieUID File set found" );
815       return;
816    }
817    while (itl != SingleSerieUIDFileSetHT.end())
818    { 
819       os << "Serie UID :[" << itl->first << "]" << std::endl;
820
821       // For all the files of a SingleSerieUID File set
822       for (FileList::iterator it =  (itl->second)->begin();
823                                   it != (itl->second)->end(); 
824                                 ++it)
825       {
826          os << indent << " --- " << (*it)->GetFileName() << std::endl;
827       }
828       ++itl;
829    }
830 }
831
832 //-----------------------------------------------------------------------------
833 } // end namespace gdcm