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