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