]> Creatis software - gdcm.git/blob - src/gdcmSerieHelper.cxx
Fix some verbosity
[gdcm.git] / src / gdcmSerieHelper.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmSerieHelper.cxx,v $
5   Language:  C++
6   Date:      $Date: 2007/06/04 08:51:24 $
7   Version:   $Revision: 1.56 $
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 : no more !
23 #include "gdcmDebug.h"
24 #include "gdcmUtil.h"
25
26 #include <math.h>
27 #include <vector>
28 #include <algorithm>
29 #include <map>
30 #include <stdio.h>  //for sscanf
31
32 namespace GDCM_NAME_SPACE
33 {
34
35 //-----------------------------------------------------------------------------
36 // Constructor / Destructor
37 /**
38  * \brief   Constructor from a given SerieHelper
39  */
40 SerieHelper::SerieHelper()
41 {
42    m_UseSeriesDetails = false;
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_NAME_SPACE::File of a File set
67       for (GDCM_NAME_SPACE::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    // Need to clear that too:
78    SingleSerieUIDFileSetHT.clear();
79 }
80
81 //-----------------------------------------------------------------------------
82
83 //-----------------------------------------------------------------------------
84
85 // Public
86 /**
87  * \brief add a GDCM_NAME_SPACE::File to the Fileset corresponding to its Serie UID
88  * @param   filename Name of the file to deal with
89  */
90 void SerieHelper::AddFileName(std::string const &filename)
91 {
92    // Create a DICOM file
93    File *header = File::New();
94    header->SetLoadMode(LoadMode);
95    header->SetFileName( filename ); 
96    header->Load();
97
98    if ( header->IsReadable() )
99    {
100       if ( !AddFile( header ) )
101       {
102          // at least one rule was unmatched we need to deallocate the file:
103          header->Delete();
104       }
105    }
106    else
107    {
108       gdcmWarningMacro("Could not read file: " << filename );
109       header->Delete();
110    }
111 }
112
113 /**
114  * \brief add a GDCM_NAME_SPACE::File to the first (and supposed to be unique) file set
115  *        of the GDCM_NAME_SPACE::SerieHelper.
116  * \warning : this method should be used by aware users only!
117  *           Passing a GDCM_NAME_SPACE::File* has the same effect than passing a file name!
118  * \todo : decide which one is wrong (the method, or the commentary)!
119  *           the following comment doesn't match the method :-(
120  *            User is supposed to know the files he want to deal with
121  *           and consider them they belong to the same Serie
122  *           (even if their Serie UID is different)
123  *           user will probabely OrderFileList() this list (actually, ordering
124  *           user choosen gdm::File is the sole interest of this method)
125  *           Moreover, using vtkGdcmReader::SetCoherentFileList() will avoid
126  *           vtkGdcmReader parsing twice the same files. 
127  *           *no* coherence check is performed, but those specified
128  *           by SerieHelper::AddRestriction()
129  * @param   header GDCM_NAME_SPACE::File* of the file to deal with
130  * @return  true if file was added, false if file was rejected
131  */
132 bool SerieHelper::AddFile(File *header)
133 {
134    int allrules = 1;
135    // First step the user has defined a set of rules for the DICOM 
136    // he is looking for.
137    // make sure the file correspond to his set of rules:
138
139    std::string s;
140    for(SerieExRestrictions::iterator it2 = ExRestrictions.begin();
141      it2 != ExRestrictions.end();
142      ++it2)
143    {
144       const ExRule &r = *it2;
145       s = header->GetEntryString( r.group, r.elem );
146       if ( !Util::CompareDicomString(s, r.value.c_str(), r.op) )
147       {
148          // Argh ! This rule is unmatched; let's just quit
149          allrules = 0;
150          break;
151       }
152    }
153
154    if ( allrules ) // all rules are respected:
155    {
156       // Allright! we have a found a DICOM that matches the user expectation. 
157       // Let's add it to the specific 'id' which by default is uid (Serie UID)
158       // but can be `refined` by user with more paramater (see AddRestriction(g,e))
159  
160       std::string id = CreateUniqueSeriesIdentifier( header );
161       // if id == GDCM_UNFOUND then consistently we should find GDCM_UNFOUND
162       // no need here to do anything special
163  
164       if ( SingleSerieUIDFileSetHT.count(id) == 0 )
165       {
166          gdcmDebugMacro(" New/gdcmSerieHelper.cxx Serie UID :[" << id << "]");
167          // create a std::list in 'id' position
168          SingleSerieUIDFileSetHT[id] = new FileList;
169       }
170       // Current Serie UID and DICOM header seems to match add the file:
171       SingleSerieUIDFileSetHT[id]->push_back( header );
172    }
173    else
174    {
175       // one rule not matched, tell user:
176       return false;
177    }
178    return true;
179 }
180
181 /**
182  * \brief add a rule for restricting a DICOM file to be in the serie we are
183  * trying to find. For example you can select only the DICOM files from a
184  * directory which would have a particular EchoTime==4.0.
185  * This method is a user level, value is not required to be formatted as a DICOM
186  * string
187  * \todo find a trick to allow user to say if he wants the Rectrictions 
188  *       to be *ored* (and not only *anded*)
189  * @param   key  Target tag we want restrict on a given value
190  * @param value value to be checked to exclude File
191  * @param op  operator we want to use to check
192  */
193 void SerieHelper::AddRestriction(TagKey const &key, 
194                                  std::string const &value, int op)
195 {
196    ExRule r;
197    r.group = key[0];
198    r.elem  = key[1];
199    r.value = value;
200    r.op    = op;
201    ExRestrictions.push_back( r ); 
202 }
203
204 void SerieHelper::AddRestriction(TagKey const &key)
205 {
206   ExRule r;
207   r.group = key[0];
208   r.elem  = key[1];
209   ExRefine.push_back( r );
210 }
211
212 //#ifndef GDCM_LEGACY_REMOVE
213 /**
214  * \brief add a rule for restricting a DICOM file to be in the serie we are
215  * trying to find. For example you can select only the DICOM files from a
216  * directory which would have a particular EchoTime==4.0.
217  * This method is a user level, value is not required to be formatted as a DICOM
218  * string
219  * @param   group tag group number we want restrict on a given value
220  * @param   elem  tag element number we want restrict on a given value 
221  * @param value value to be checked to exclude File
222  * @param op  operator we want to use to check
223  * @deprecated use : AddRestriction(TagKey const &key, 
224  *                                 std::string const &value, int op);
225  */
226
227 void SerieHelper::AddRestriction(uint16_t group, uint16_t elem, 
228                                  std::string const &value, int op)
229 {
230   TagKey t(group, elem);
231   AddRestriction(t, value, op);
232 }
233
234 //#endif
235
236 /**
237  * \brief add an extra  'SerieDetail' for building a 'Serie Identifier'
238  *        that ensures (hope so) File constistency (Series Instance UID doesn't.
239  * @param   group tag group number we want restrict on a given value
240  * @param   elem  tag element number we want restrict on a given value
241  * @param  convert wether we want 'convertion', to allow further ordering
242  *         e.g : 100 would be *before* 20; 000020.00 vs 00100.00 : OK 
243  */
244 void SerieHelper::AddSeriesDetail(uint16_t group, uint16_t elem, bool convert)
245 {
246    
247    ExDetail d;
248    d.group   = group;
249    d.elem    = elem;
250    d.convert = convert;
251    ExDetails.push_back( d ); 
252 }
253 /**
254  * \brief Sets the root Directory
255  * @param   dir Name of the directory to deal with
256  * @param recursive whether we want explore recursively the root Directory
257  */
258 void SerieHelper::SetDirectory(std::string const &dir, bool recursive)
259 {
260    DirList dirList(dir, recursive); // OS specific
261   
262    DirListType filenames_list = dirList.GetFilenames();
263    for( DirListType::const_iterator it = filenames_list.begin(); 
264         it != filenames_list.end(); ++it)
265    {
266       AddFileName( *it );
267    }
268 }
269
270 /**
271  * \brief Sorts the given Fileset
272  * \warning This could be implemented in a 'Strategy Pattern' approach
273  *          But as I don't know how to do it, I leave it this way
274  *          BTW, this is also a Strategy, I don't know this is 
275  *          the best approach :)
276  */
277 void SerieHelper::OrderFileList(FileList *fileSet)
278 {
279    // Only computed during ImagePositionPatientOrdering
280    // (need to sort the FileList using IPP and IOP !)
281    ZSpacing = -1.0;
282    
283    if ( SerieHelper::UserLessThanFunction )
284    {
285       UserOrdering( fileSet );
286       return; 
287    }
288    else if ( ImagePositionPatientOrdering( fileSet ) )
289    {
290       return ;
291    }
292    else if ( ImageNumberOrdering(fileSet ) )
293    {
294       return ;
295    }
296    else  
297    {
298       FileNameOrdering(fileSet );
299    }
300 }
301
302 /**
303  * \brief Elementary coherence checking of the files with the same Serie UID
304  * Only sizes and pixel type are checked right now ...
305  */ 
306 bool SerieHelper::IsCoherent(FileList *fileSet)
307 {
308    if(fileSet->size() == 1)
309    return true;
310
311    FileList::const_iterator it = fileSet->begin();
312
313    int nX =               (*it)->GetXSize();
314    int nY =               (*it)->GetYSize();
315    int pixelSize =        (*it)->GetPixelSize();
316    bool signedPixelData = (*it)->IsSignedPixelData();
317    it ++;
318    for ( ;
319          it != fileSet->end();
320        ++it)
321    {
322       if ( (*it)->GetXSize() != nX )
323          return false;
324       if ( (*it)->GetYSize() != nY )
325          return false;
326       if ( (*it)->GetPixelSize() != pixelSize )
327          return false;
328       if ( (*it)->IsSignedPixelData() != signedPixelData )
329          return false;
330       // probabely more is to be checked (?)
331    }
332    return true;
333 }
334
335 //#ifndef GDCM_LEGACY_REMOVE
336 /**
337  * \brief   accessor (DEPRECATED :  use GetFirstSingleSerieUIDFileSet )
338  *          Warning : 'coherent' means here they have the same Serie UID
339  * @return  The first FileList if found, otherwhise NULL
340  */
341  /*
342 FileList *SerieHelper::GetFirstCoherentFileList()
343 {
344    ItFileSetHt = SingleSerieUIDFileSetHT.begin();
345    if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
346       return ItFileSetHt->second;
347    return NULL;
348 }
349 */
350 /**
351  * \brief   accessor (DEPRECATED :  use GetNextSingleSerieUIDFileSet )
352  *          Warning : 'coherent' means here they have the same Serie UID
353  * \note : meaningfull only if GetFirstCoherentFileList() already called 
354  * @return  The next FileList if found, otherwhise NULL
355  */
356  /*
357 FileList *SerieHelper::GetNextCoherentFileList()
358 {
359    gdcmAssertMacro (ItFileSetHt != SingleSerieUIDFileSetHT.end());
360   
361    ++ItFileSetHt;
362    if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
363       return ItFileSetHt->second;
364    return NULL;
365 }
366 */
367
368 /**
369  * \brief   accessor (DEPRECATED :  use GetSingleSerieUIDFileSet )
370   *          Warning : 'coherent' means here they have the same Serie UID
371  * @param SerieUID SerieUID
372  * \return  pointer to the FileList if found, otherwhise NULL
373  */
374  /*
375 FileList *SerieHelper::GetCoherentFileList(std::string SerieUID)
376 {
377    if ( SingleSerieUIDFileSetHT.count(SerieUID) == 0 )
378       return 0;     
379    return SingleSerieUIDFileSetHT[SerieUID];
380 }
381 */
382 //#endif
383
384
385 /**
386  * \brief   Get the first Fileset while visiting the SingleSerieUIDFileSetmap
387  * @return  The first FileList (SingleSerieUIDFileSet) if found, otherwhise 0
388  */
389 FileList *SerieHelper::GetFirstSingleSerieUIDFileSet()
390 {
391    ItFileSetHt = SingleSerieUIDFileSetHT.begin();
392    if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
393       return ItFileSetHt->second;
394    return NULL;
395 }
396
397 /**
398  * \brief   Get the next Fileset while visiting the SingleSerieUIDFileSetmap
399  * \note : meaningfull only if GetNextSingleSerieUIDFileSet() already called 
400  * @return  The next FileList (SingleSerieUIDFileSet) if found, otherwhise 0
401  */
402 FileList *SerieHelper::GetNextSingleSerieUIDFileSet()
403 {
404    gdcmAssertMacro (ItFileSetHt != SingleSerieUIDFileSetHT.end());
405   
406    ++ItFileSetHt;
407    if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
408       return ItFileSetHt->second;
409    return NULL;
410 }
411
412 /**
413  * \brief   Get the SingleSerieUIDFileSet according to its Serie UID
414  * @param SerieUID SerieUID to retrieve
415  * \return pointer to the FileList (SingleSerieUIDFileSet) if found, otherwhise 0
416  */
417 FileList *SerieHelper::GetSingleSerieUIDFileSet(std::string SerieUID)
418 {
419    if ( SingleSerieUIDFileSetHT.count(SerieUID) == 0 )
420       return 0;     
421    return SingleSerieUIDFileSetHT[SerieUID];
422 }
423
424 /**
425  * \brief   Splits a Single SerieUID Fileset according to the Orientations
426  * @param fileSet File Set to be splitted
427  * \return  std::map of 'Xcoherent' File sets
428  */
429
430 XCoherentFileSetmap SerieHelper::SplitOnOrientation(FileList *fileSet)
431 {
432    XCoherentFileSetmap CoherentFileSet;
433
434    int nb = fileSet->size();
435    if (nb == 0 )
436       return CoherentFileSet;
437    float iop[6];
438    std::string strOrient;
439    std::ostringstream ossOrient;
440
441    FileList::const_iterator it = fileSet->begin();
442    it ++;
443    for ( ;
444          it != fileSet->end();
445        ++it)
446    {     
447       // Information is in :      
448       // 0020 0037 : Image Orientation (Patient) or
449       // 0020 0035 : Image Orientation (RET)
450
451       // Let's build again the 'cosines' string, to be sure of it's format      
452       (*it)->GetImageOrientationPatient(iop);
453
454       ossOrient << iop[0];      
455       for (int i = 1; i < 6; i++)
456       {
457         ossOrient << "\\";
458         ossOrient << iop[i]; 
459       }      
460       strOrient = ossOrient.str();
461       ossOrient.str("");
462       if ( CoherentFileSet.count(strOrient) == 0 )
463       {
464          gdcmDebugMacro(" New Orientation :[" << strOrient << "]");
465          // create a File set in 'orientation' position
466          CoherentFileSet[strOrient] = new FileList;
467       }
468       // Current Orientation and DICOM header match; add the file:
469       CoherentFileSet[strOrient]->push_back( (*it) );
470    }
471    return CoherentFileSet;
472 }
473
474 /**
475  * \brief   Splits a 'Single SerieUID' Fileset according to the Positions
476  * @param fileSet File Set to be splitted
477  * \return  std::map of 'Xcoherent' File sets
478  */
479
480 XCoherentFileSetmap SerieHelper::SplitOnPosition(FileList *fileSet)
481 {
482    XCoherentFileSetmap CoherentFileSet;
483
484    int nb = fileSet->size();
485    if (nb == 0 )
486       return CoherentFileSet;
487    float pos[3];
488    std::string strImPos;  // read on disc
489    std::ostringstream ossPosition;
490    std::string strPosition; // re computed
491    FileList::const_iterator it = fileSet->begin();
492    it ++;
493    for ( ;
494          it != fileSet->end();
495        ++it)
496    {     
497       // Information is in :      
498       // 0020,0032 : Image Position Patient
499       // 0020,0030 : Image Position (RET)
500
501       strImPos = (*it)->GetEntryString(0x0020,0x0032);
502       if ( strImPos == GDCM_UNFOUND)
503       {
504          gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
505          strImPos = (*it)->GetEntryString(0x0020,0x0030); // For ACR-NEMA images
506          if ( strImPos == GDCM_UNFOUND )
507          {
508             gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
509             // User wants to split on the 'Position'
510             // No 'Position' info found.
511             // We return an empty Htable !
512             return CoherentFileSet;
513          }  
514       }
515
516       if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", 
517                                               &pos[0], &pos[1], &pos[2]) != 3 )
518       {
519             gdcmWarningMacro( "Wrong number for Position : ["
520                        << strImPos << "]" );
521              return CoherentFileSet;
522       }
523
524       // Let's build again the 'position' string, to be sure of it's format      
525
526       ossPosition << pos[0];      
527       for (int i = 1; i < 3; i++)
528       {
529         ossPosition << "\\";
530         ossPosition << pos[i]; 
531       }      
532       strPosition = ossPosition.str();
533       ossPosition.str("");
534
535       if ( CoherentFileSet.count(strPosition) == 0 )
536       {
537          gdcmDebugMacro(" New Position :[" << strPosition << "]");
538          // create a File set in 'position' position
539          CoherentFileSet[strPosition] = new FileList;
540       }
541       // Current Position and DICOM header match; add the file:
542       CoherentFileSet[strPosition]->push_back( (*it) );
543    }   
544    return CoherentFileSet;
545 }
546
547 /**
548  * \brief   Splits a 'Single SerieUID' File set Coherent according to the
549  *          value of a given Tag
550  * @param fileSet File Set to be splitted
551  * @param   group  group number of the target Element
552  * @param   element element number of the target Element
553  * \return  std::map of 'Xcoherent' File sets
554  */
555
556 XCoherentFileSetmap SerieHelper::SplitOnTagValue(FileList *fileSet, 
557                                                uint16_t group, uint16_t element)
558 {
559    XCoherentFileSetmap CoherentFileSet;
560
561    int nb = fileSet->size();
562    if (nb == 0 )
563       return CoherentFileSet;
564
565    std::string strTagValue;  // read on disc
566
567    FileList::const_iterator it = fileSet->begin();
568    it ++;
569    for ( ;
570          it != fileSet->end();
571        ++it)
572    {     
573       // Information is in :      
574       // 0020,0032 : Image Position Patient
575       // 0020,0030 : Image Position (RET)
576
577       strTagValue = (*it)->GetEntryString(group,element);
578       
579       if ( CoherentFileSet.count(strTagValue) == 0 )
580       {
581          gdcmDebugMacro(" New Tag Value :[" << strTagValue << "]");
582          // create a File set in 'position' position
583          CoherentFileSet[strTagValue] = new FileList;
584       }
585       // Current Tag value and DICOM header match; add the file:
586       CoherentFileSet[strTagValue]->push_back( (*it) );
587    }
588    return CoherentFileSet;
589 }
590
591 //-----------------------------------------------------------------------------
592 // Protected
593
594 //-----------------------------------------------------------------------------
595 // Private
596 /**
597  * \brief sorts the images, according to their Patient Position.
598  *  As a side effect, it computes the ZSpacing, according to Jolinda Smith'
599  *  algorithm. (get it with double GetZSpacing() !)
600  *  We may order, considering :
601  *   -# Image Position Patient
602  *   -# Image Number
603  *   -# file name
604  *   -# More to come :-)
605  * \note : FileList = std::vector<File* >
606  * @param fileList Coherent File list (same Serie UID) to sort
607  * @return false only if the header is bugged !
608  */
609 bool SerieHelper::ImagePositionPatientOrdering( FileList *fileList )
610 //based on Jolinda Smith's algorithm
611 {
612 //Tags always use the same coordinate system, where "x" is left
613 //to right, "y" is posterior to anterior, and "z" is foot to head (RAH).
614
615    //iop is calculated based on the file file
616    float cosines[6];
617    double normal[3];
618    double ipp[3];
619    double dist;
620    double min = 0, max = 0;
621    bool first = true;
622    ZSpacing = -1.0;  // will be updated if process doesn't fail
623
624    std::multimap<double,File *> distmultimap;
625    // Use a multimap to sort the distances from 0,0,0
626    for ( FileList::const_iterator 
627          it = fileList->begin();
628          it != fileList->end(); ++it )
629    {
630       if ( first ) 
631       {
632          (*it)->GetImageOrientationPatient( cosines );
633
634    // The "Image Orientation Patient" tag gives the direction cosines 
635    // for the rows and columns for the three axes defined above. 
636    // Typical axial slices will have a value 1/0/0/0/1/0: 
637    // rows increase from left to right, 
638    // columns increase from posterior to anterior. This is your everyday
639    // "looking up from the bottom of the head with the eyeballs up" image. 
640    
641    // The "Image Position Patient" tag gives the coordinates of the first
642    // voxel in the image in the "RAH" coordinate system, relative to some
643    // origin.   
644
645    // First, calculate the slice normal from IOP : 
646           
647          // You only have to do this once for all slices in the volume. Next, 
648          // for each slice, calculate the distance along the slice normal 
649          // using the IPP ("Image Position Patient") tag.
650          // ("dist" is initialized to zero before reading the first slice) :
651          normal[0] = cosines[1]*cosines[5] - cosines[2]*cosines[4];
652          normal[1] = cosines[2]*cosines[3] - cosines[0]*cosines[5];
653          normal[2] = cosines[0]*cosines[4] - cosines[1]*cosines[3];
654
655    // For each slice (here : the first), calculate the distance along 
656    // the slice normal using the IPP tag 
657     
658          ipp[0] = (*it)->GetXOrigin();
659          ipp[1] = (*it)->GetYOrigin();
660          ipp[2] = (*it)->GetZOrigin();
661
662          dist = 0;
663          for ( int i = 0; i < 3; ++i )
664          {
665             dist += normal[i]*ipp[i];
666          }
667     
668          distmultimap.insert(std::pair<const double,File *>(dist, *it));
669
670          max = min = dist;
671          first = false;
672       }
673       else 
674       {
675    // Next, for each slice, calculate the distance along the slice normal
676    // using the IPP tag 
677          ipp[0] = (*it)->GetXOrigin();
678          ipp[1] = (*it)->GetYOrigin();
679          ipp[2] = (*it)->GetZOrigin();
680
681          dist = 0;
682          for ( int i = 0; i < 3; ++i )
683          {
684             dist += normal[i]*ipp[i];
685          }
686
687          distmultimap.insert(std::pair<const double,File *>(dist, *it));
688
689          min = (min < dist) ? min : dist;
690          max = (max > dist) ? max : dist;
691       }
692    }
693
694    // Find out if min/max are coherent
695    if ( min == max )
696    {
697      gdcmWarningMacro("Looks like all images have the exact same image position. "
698                       << "No PositionPatientOrdering sort performed. " 
699                       << "No 'ZSpacing' calculated! ");
700      return false;
701    }
702
703    // Check to see if image shares a common position
704    bool ok = true;
705    for (std::multimap<double, File *>::iterator it2 = distmultimap.begin();
706         it2 != distmultimap.end();
707         ++it2)
708    {
709       if (distmultimap.count((*it2).first) != 1)
710       {
711          gdcmErrorMacro("File: ["
712               << ((*it2).second->GetFileName())
713               << "] : more than ONE file at distance: '"
714               << (*it2).first
715               << " (position is not unique!) " 
716               << "No PositionPatientOrdering sort performed. " 
717               << "No 'ZSpacing' calculated! ");      
718
719          ok = false;
720       }
721    }
722    if (!ok)
723    {
724       return false;
725    }
726
727 // Now, we could calculate Z Spacing as the difference
728 // between the "dist" values for the first two slices.
729
730 // The following (un)-commented out code is let here
731 // to be re-used by whomsoever is interested...
732
733     std::multimap<double, File *>::iterator it5 = distmultimap.begin();
734     double d1 = (*it5).first;
735     it5++;
736     double d2 = (*it5).first;
737     ZSpacing = d1-d2;
738     if (ZSpacing < 0.0)
739        ZSpacing = - ZSpacing;
740
741    fileList->clear();  // doesn't delete list elements, only nodes
742
743 // Acording to user requierement, we sort direct order or reverse order.
744    if (DirectOrder)
745    {  
746       for (std::multimap<double, File *>::iterator it3 = distmultimap.begin();
747            it3 != distmultimap.end();
748            ++it3)
749       {
750          fileList->push_back( (*it3).second );
751       }
752    }
753    else // user asked for reverse order
754    {
755       std::multimap<double, File *>::const_iterator it4;
756       it4 = distmultimap.end();
757       do
758       {
759          it4--;
760          fileList->push_back( (*it4).second );
761       } while (it4 != distmultimap.begin() );
762    }
763
764    distmultimap.clear();
765
766    return true;
767 }
768
769 bool SerieHelper::ImageNumberLessThan(File *file1, File *file2)
770 {
771   return file1->GetImageNumber() < file2->GetImageNumber();
772 }
773
774 bool SerieHelper::ImageNumberGreaterThan(File *file1, File *file2)
775 {
776   return file1->GetImageNumber() > file2->GetImageNumber();
777 }
778
779 /**
780  * \brief sorts the images, according to their Image Number
781  * \note Works only on bona fide files  (i.e image number is a character string
782  *                                      corresponding to an integer)
783  *             within a bona fide serie (i.e image numbers are consecutive)
784  * @param fileList File set (same Serie UID) to sort 
785  * @return false if non bona fide stuff encountered
786  */
787 bool SerieHelper::ImageNumberOrdering(FileList *fileList) 
788 {
789    int min, max, pos;
790    int n = fileList->size();
791
792    FileList::const_iterator it = fileList->begin();
793    min = max = (*it)->GetImageNumber();
794
795    for (; it != fileList->end(); ++it, ++n)
796    {
797       pos = (*it)->GetImageNumber();
798       min = (min < pos) ? min : pos;
799       max = (max > pos) ? max : pos;
800    }
801
802    // Find out if image numbers are coherent (consecutive)
803    if ( min == max || max == 0 || max >= (n+min) )
804    {
805       gdcmWarningMacro( " 'Image numbers' not coherent. "
806                         << " No ImageNumberOrdering sort performed.");
807       return false;
808    }
809    if (DirectOrder)
810       Sort(fileList,SerieHelper::ImageNumberLessThan);
811    else
812       Sort(fileList,SerieHelper::ImageNumberGreaterThan);
813
814    return true;
815 }
816
817 bool SerieHelper::FileNameLessThan(File *file1, File *file2)
818 {
819    return file1->GetFileName() < file2->GetFileName();
820 }
821
822 bool SerieHelper::FileNameGreaterThan(File *file1, File *file2)
823 {
824    return file1->GetFileName() > file2->GetFileName();
825 }
826 /**
827  * \brief sorts the images, according to their File Name
828  * @param fileList Coherent File list (same Serie UID) to sort
829  * @return false only if the header is bugged !
830  */
831 bool SerieHelper::FileNameOrdering(FileList *fileList)
832 {
833    if (DirectOrder) 
834       Sort(fileList,SerieHelper::FileNameLessThan);
835    else
836       Sort(fileList,SerieHelper::FileNameGreaterThan);   
837
838    return true;
839 }
840
841 /**
842  * \brief sorts the images, according to user supplied function
843  * @param fileList Coherent File list (same Serie UID) to sort
844  * @return false only if the header is bugged !
845  */
846 bool SerieHelper::UserOrdering(FileList *fileList)
847 {
848    Sort(fileList,SerieHelper::UserLessThanFunction);   
849    if (!DirectOrder) 
850    {
851       std::reverse(fileList->begin(), fileList->end());
852    }
853    return true;
854 }
855
856 //-----------------------------------------------------------------------------
857 // Print
858 /**
859  * \brief   Canonical printer.
860  */
861 void SerieHelper::Print(std::ostream &os, std::string const &indent)
862 {
863    // For all the Coherent File lists of the GDCM_NAME_SPACE::Serie
864    SingleSerieUIDFileSetmap::iterator itl = SingleSerieUIDFileSetHT.begin();
865    if ( itl == SingleSerieUIDFileSetHT.end() )
866    {
867       gdcmWarningMacro( "No SingleSerieUID File set found" );
868       return;
869    }
870    while (itl != SingleSerieUIDFileSetHT.end())
871    { 
872       os << "Serie UID :[" << itl->first << "]" << std::endl;
873
874       // For all the files of a SingleSerieUID File set
875       for (FileList::iterator it =  (itl->second)->begin();
876                                   it != (itl->second)->end(); 
877                                 ++it)
878       {
879          os << indent << " --- " << (*it)->GetFileName() << std::endl;
880       }
881       ++itl;
882    }
883 }
884
885 void SerieHelper::CreateDefaultUniqueSeriesIdentifier()
886 {
887    // If the user requests, additional information can be appended
888    // to the SeriesUID to further differentiate volumes in the DICOM
889    // objects being processed.
890  
891    // 0020 0011 Series Number
892    // A scout scan prior to a CT volume scan can share the same
893    //   SeriesUID, but they will sometimes have a different Series Number
894    AddRestriction( TagKey(0x0020, 0x0011) );
895    
896    // 0018 0024 Sequence Name
897    // For T1-map and phase-contrast MRA, the different flip angles and
898    //   directions are only distinguished by the Sequence Name
899    AddRestriction( TagKey(0x0018, 0x0024) );
900    
901    // 0018 0050 Slice Thickness
902    // On some CT systems, scout scans and subsequence volume scans will
903    //   have the same SeriesUID and Series Number - YET the slice 
904    //   thickness will differ from the scout slice and the volume slices.
905    AddRestriction( TagKey(0x0018, 0x0050));
906    
907    // 0028 0010 Rows
908    // If the 2D images in a sequence don't have the same number of rows,
909    // then it is difficult to reconstruct them into a 3D volume.
910    AddRestriction( TagKey(0x0028, 0x0010));
911    
912    // 0028 0011 Columns
913    // If the 2D images in a sequence don't have the same number of columns,
914    // then it is difficult to reconstruct them into a 3D volume.
915    AddRestriction( TagKey(0x0028, 0x0011));
916 }
917
918 /**
919  * \brief Heuristics to *try* to build a Serie Identifier that would ensure
920  *        all the images are coherent.
921  *
922  * By default, uses the SeriesUID.  If UseSeriesDetails(true) has been called,
923  *         then additional identifying information is used.
924  *  We allow user to add his own critierions, using AddSeriesDetail
925  *        (he knows more than we do about his images!)
926  *        ex : in tagging series, the only pertnent tag is
927  *        0018|1312 [In-plane Phase Encoding Direction] value : ROW/COLUMN
928  * @param inFile GDCM_NAME_SPACE::File we want to build a Serie Identifier for.
929  * @return the SeriesIdentifier
930  */
931 std::string SerieHelper::CreateUniqueSeriesIdentifier( File *inFile )
932 {
933    if( inFile->IsReadable() )
934    {
935     // 0020 000e UI REL Series Instance UID
936     std::string uid = inFile->GetEntryString (0x0020, 0x000e);
937     std::string id = uid.c_str();
938     if(m_UseSeriesDetails)
939       {
940       for(SerieExRestrictions::iterator it2 = ExRefine.begin();
941         it2 != ExRefine.end();
942         ++it2)
943         {
944         const ExRule &r = *it2;
945         std::string s = inFile->GetEntryString( r.group, r.elem );
946         if( s == GDCM_UNFOUND )
947           {
948           s = "";
949           }
950         if( id == uid && !s.empty() )
951           {
952           id += "."; // add separator
953           }
954         id += s;
955         }
956       }
957     // Eliminate non-alnum characters, including whitespace...
958     //   that may have been introduced by concats.
959     for(unsigned int i=0; i<id.size(); i++)
960       {
961       while(i<id.size() 
962         && !( id[i] == '.'
963           || (id[i] >= 'a' && id[i] <= 'z')
964           || (id[i] >= '0' && id[i] <= '9')
965           || (id[i] >= 'A' && id[i] <= 'Z')))
966         {
967         id.erase(i, 1);
968         }
969       }
970     return id;
971     }
972   else // Could not open inFile
973     {
974     gdcmWarningMacro("Could not parse series info.");
975     std::string id = GDCM_UNFOUND;
976     return id;
977     }
978 }
979
980 /**
981  * \brief Allow user to build is own File Identifier (to be able to sort
982  *        temporal series just as he wants)
983  *        Criterions will be set with AddSeriesDetail.
984  *        (Maybe the method should be moved elsewhere 
985  *       -File class? FileHelper class?-
986  * @return FileIdentifier (Tokenizable on '%%%'. Hope it's enough !)
987  */
988 std::string SerieHelper::CreateUserDefinedFileIdentifier( File * inFile )
989 {
990   //     Deal with all user supplied tags.
991   //      (user knows more than we do about his images!)
992   
993    double converted;
994    std::string id;
995    std::string s; 
996    char charConverted[17]; 
997    
998    for(SeriesExDetails::iterator it2 = ExDetails.begin();
999       it2 != ExDetails.end();
1000       ++it2)
1001    {
1002       const ExDetail &r = *it2;
1003       s = inFile->GetEntryString( r.group, r.elem );
1004
1005       // User is allowed to ask for 'convertion', to allow further ordering
1006       // e.g : 100 would be *before* 20; 000020.00 vs 00100.00 : OK
1007       if (it2->convert)
1008       {
1009          if ( s != GDCM_UNFOUND) // Don't convert unfound fields !
1010          {
1011             converted = atof(s.c_str());
1012             // probabely something much more complicated is possible, 
1013             // using C++ features
1014             /// \todo check the behaviour when there are >0 and <0 numbers
1015             sprintf(charConverted, "%016.6f",converted);
1016             s = charConverted;
1017          }
1018       }
1019       // Eliminate non-alphanum characters, including whitespace.
1020       for(unsigned int i=0; i<s.size(); i++)
1021       {
1022          while(i<s.size()
1023                && !( s[i] == '.' || s[i] == '%'
1024                  || (s[i] >= 'a' && s[i] <= 'z')
1025                  || (s[i] >= '0' && s[i] <= '9')
1026                  || (s[i] >= 'A' && s[i] <= 'Z')))
1027          {
1028             s.erase(i, 1);
1029          }
1030       }
1031       
1032       id += s.c_str();
1033       id += "%%%"; // make the FileIdentifier Tokenizable
1034    }
1035    
1036    return id;             
1037 }
1038
1039 //-----------------------------------------------------------------------------
1040 // Sort
1041 /**
1042  * \brief   Sort FileList.
1043  */
1044 void SerieHelper::Sort(FileList *fileList, bool (*pt2Func)( File *file1, File *file2) )
1045 {
1046  std::sort(fileList->begin(), fileList->end(), pt2Func );
1047 }
1048
1049 /*
1050 #ifndef GDCM_LEGACY_REMOVE
1051 bool SerieHelper::AddGdcmFile(File* header)
1052 {
1053   return AddFile(header);
1054 }
1055 #endif
1056 */
1057
1058 //-----------------------------------------------------------------------------
1059 } // end namespace gdcm