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