]> Creatis software - gdcm.git/blob - src/gdcmDicomDir.cxx
* Remove memory leaks on the DicomDir
[gdcm.git] / src / gdcmDicomDir.cxx
1 /*=========================================================================
2   
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDicomDir.cxx,v $
5   Language:  C++
6   Date:      $Date: 2004/12/03 17:13:18 $
7   Version:   $Revision: 1.84 $
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 "gdcmDicomDir.h"
20 #include "gdcmDicomDirStudy.h"
21 #include "gdcmDicomDirSerie.h"
22 #include "gdcmDicomDirImage.h"
23 #include "gdcmDirList.h"
24 #include "gdcmUtil.h"
25 #include "gdcmDebug.h"
26 #include "gdcmGlobal.h"
27 #include "gdcmHeader.h"
28 #include "gdcmSeqEntry.h"
29 #include "gdcmSQItem.h"
30 #include "gdcmValEntry.h"
31
32 #include <fstream>
33 #include <string>
34 #include <algorithm>
35 #include <sys/types.h>
36
37 #ifdef _MSC_VER
38 #define getcwd _getcwd
39 #endif
40
41 #if defined( _MSC_VER) || defined(__BORLANDC__)
42    #include <direct.h>
43 #else
44    #include <unistd.h>
45 #endif
46
47 namespace gdcm 
48 {
49
50 //-----------------------------------------------------------------------------
51 //  For full DICOMDIR description, see:
52 //  PS 3.3-2003, pages 731-750
53 //-----------------------------------------------------------------------------
54 // Constructor / Destructor
55
56 /**
57  * \ingroup DicomDir
58  * \brief   Constructor : creates an empty DicomDir
59  */
60 DicomDir::DicomDir()
61    :Document( )
62
63    Initialize();  // sets all private fields to NULL
64    MetaElems = NewMeta();
65 }
66
67 /**
68  * \brief Constructor Parses recursively the directory and creates the DicomDir
69  *        or uses an already built DICOMDIR, depending on 'parseDir' value.
70  * @param fileName        name 
71  *                      - of the root directory (parseDir = true)
72  *                      - of the DICOMDIR       (parseDir = false)
73  * @param parseDir boolean
74  *                      - true if user passed an entry point 
75  *                        and wants to explore recursively the directories
76  *                      - false if user passed an already built DICOMDIR file
77  *                        and wants to use it 
78  */
79 DicomDir::DicomDir(std::string const & fileName, bool parseDir ):
80    Document( fileName )
81 {
82    // Whatever user passed (a root directory or a DICOMDIR)
83    // and whatever the value of parseDir was,
84    // Document is already executed
85    Initialize();  // sets all private fields to NULL
86
87    // if user passed a root directory, sure we didn't get anything
88    if ( TagHT.begin() == TagHT.end() ) // when user passed a Directory to parse
89    {
90       dbg.Verbose(0, "DicomDir::DicomDir : entry HT empty");
91
92       if ( fileName.size() == 1 && fileName[0] == '.' )
93       {
94          // user passed '.' as Name
95          // we get current directory name
96          char dummy[1000];
97          getcwd(dummy, (size_t)1000);
98          SetFileName( dummy ); // will be converted into a string
99       }
100
101       if ( parseDir ) // user asked for a recursive parsing of a root directory
102       {
103          MetaElems = NewMeta();
104
105          dbg.Verbose(0, "DicomDir::DicomDir : Parse directory"
106                         " and create the DicomDir");
107          ParseDirectory();
108       }
109       else
110       {
111          /// \todo if parseDir == false, it should be tagged as an error
112          // NON ! il suffit d'appeler ParseDirectory() 
113          // apres le constructeur
114       }
115    }
116    else // Only if user passed a DICOMDIR
117    {
118       // Directory record sequence
119       DocEntry *e = GetDocEntryByNumber(0x0004, 0x1220);
120       if ( !e )
121       {
122          dbg.Verbose(0, "DicomDir::DicomDir : NO Directory record"
123                         " sequence (0x0004,0x1220)");
124          /// \todo FIXME : what do we do when the parsed file IS NOT a
125          ///       DICOMDIR file ?         
126       }
127       else
128          CreateDicomDir();
129    }
130 }
131
132 /**
133  * \brief  Canonical destructor 
134  */
135 DicomDir::~DicomDir() 
136 {
137    SetStartMethod(NULL);
138    SetProgressMethod(NULL);
139    SetEndMethod(NULL);
140
141    for(ListDicomDirPatient::iterator cc = Patients.begin();
142                                      cc!= Patients.end();
143                                    ++cc)
144    {
145       delete *cc;
146    }
147    if ( MetaElems )
148    {
149       delete MetaElems;
150    }
151 }
152
153 //-----------------------------------------------------------------------------
154 // Print
155 /**
156  * \brief  Canonical Printer 
157  */
158 void DicomDir::Print(std::ostream &os)
159 {
160    if( MetaElems )
161    {
162       MetaElems->SetPrintLevel(PrintLevel);
163       MetaElems->Print(os);   
164    }   
165    for(ListDicomDirPatient::iterator cc  = Patients.begin();
166                                      cc != Patients.end();
167                                    ++cc)
168    {
169      (*cc)->SetPrintLevel( PrintLevel );
170      (*cc)->Print( os );
171    }
172 }
173
174 //-----------------------------------------------------------------------------
175 // Public
176 /**
177  * \brief  This predicate, based on hopefully reasonable heuristics,
178  *         decides whether or not the current header was properly parsed
179  *         and contains the mandatory information for being considered as
180  *         a well formed and usable DicomDir.
181  * @return true when Document is the one of a reasonable DicomDir,
182  *         false otherwise. 
183  */
184 bool DicomDir::IsReadable()
185 {
186    if( !Document::IsReadable() )
187    {
188       return false;
189    }
190    if( !MetaElems )
191    {
192       return false;
193    }
194    if( Patients.size() <= 0 )
195    {
196       return false;
197    }
198
199    return true;
200 }
201
202 /**
203  * \brief Sets all fields to NULL
204  */
205
206 void DicomDir::Initialize()
207 {
208    StartMethod             = NULL;
209    ProgressMethod          = NULL;
210    EndMethod               = NULL;
211    StartMethodArgDelete    = NULL;
212    ProgressMethodArgDelete = NULL;
213    EndMethodArgDelete      = NULL;
214    StartArg                = NULL;
215    ProgressArg             = NULL;
216    EndArg                  = NULL;
217
218    Progress = 0.0;
219    Abort = false;
220
221    MetaElems = NULL;   
222 }
223
224
225 /**
226  * \ingroup DicomDir
227  * \brief  fills the whole structure, starting from a root Directory
228  */
229 void DicomDir::ParseDirectory()
230 {
231    CreateDicomDirChainedList( GetFileName() );
232    CreateDicomDir();
233 }
234
235 /**
236  * \ingroup DicomDir
237  * \brief   Set the start method to call when the parsing of the
238  *          directory starts.
239  * @param   method Method to call
240  * @param   arg    Argument to pass to the method
241  * @param   argDelete    Argument 
242  * \warning In python : the arg parameter isn't considered
243  */
244 void DicomDir::SetStartMethod( DicomDir::Method* method, void* arg, 
245                                DicomDir::Method* argDelete )
246 {
247    if( StartArg && StartMethodArgDelete )
248    {
249       StartMethodArgDelete( StartArg );
250    }
251
252    StartMethod          = method;
253    StartArg             = arg;
254    StartMethodArgDelete = argDelete;
255 }
256
257 /**
258  * \ingroup DicomDir
259  * \brief   Set the method to delete the argument
260  *          The argument is destroyed when the method is changed or when the
261  *          class is destroyed
262  * @param   method Method to call to delete the argument
263  */
264 void DicomDir::SetStartMethodArgDelete( DicomDir::Method* method ) 
265 {
266    StartMethodArgDelete = method;
267 }
268
269 /**
270  * \ingroup DicomDir
271  * \brief   Set the progress method to call when the parsing of the
272  *          directory progress
273  * @param   method Method to call
274  * @param   arg    Argument to pass to the method
275  * @param   argDelete    Argument  
276  * \warning In python : the arg parameter isn't considered
277  */
278 void DicomDir::SetProgressMethod( DicomDir::Method* method, void* arg, 
279                                   DicomDir::Method* argDelete )
280 {
281    if( ProgressArg && ProgressMethodArgDelete )
282    {
283       ProgressMethodArgDelete( ProgressArg );
284    }
285
286    ProgressMethod          = method;
287    ProgressArg             = arg;
288    ProgressMethodArgDelete = argDelete;
289 }
290
291 /**
292  * \ingroup DicomDir
293  * \brief   Set the method to delete the argument
294  *          The argument is destroyed when the method is changed or when the 
295  *          class is destroyed          
296  * @param   method Method to call to delete the argument
297  */
298 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method* method )
299 {
300    ProgressMethodArgDelete = method;
301 }
302
303 /**
304  * \ingroup DicomDir
305  * \brief   Set the end method to call when the parsing of the directory ends
306  * @param   method Method to call
307  * @param   arg    Argument to pass to the method
308  * @param   argDelete    Argument 
309  * \warning In python : the arg parameter isn't considered
310  */
311 void DicomDir::SetEndMethod( DicomDir::Method* method, void* arg, 
312                              DicomDir::Method* argDelete )
313 {
314    if( EndArg && EndMethodArgDelete )
315    {
316       EndMethodArgDelete( EndArg );
317    }
318
319    EndMethod          = method;
320    EndArg             = arg;
321    EndMethodArgDelete = argDelete;
322 }
323
324 /**
325  * \ingroup DicomDir
326  * \brief   Set the method to delete the argument
327  *          The argument is destroyed when the method is changed or when
328  *          the class is destroyed
329  * @param   method Method to call to delete the argument
330  */
331 void DicomDir::SetEndMethodArgDelete( DicomDir::Method* method )
332 {
333    EndMethodArgDelete = method;
334 }
335
336 /**
337  * \ingroup DicomDir
338  * \brief    writes on disc a DICOMDIR
339  * \ warning does NOT add the missing elements in the header :
340  *           it's up to the user doing it !
341  * \todo : to be re-written using the DICOMDIR tree-like structure
342  *         *not* the chained list
343  *         (does NOT exist if the DICOMDIR is user-forged !)
344  * @param  fileName file to be written to 
345  * @return false only when fail to open
346  */
347  
348 bool DicomDir::WriteDicomDir(std::string const& fileName) 
349 {  
350    int i;
351    uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
352    uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
353
354    std::ofstream* fp = new std::ofstream(fileName.c_str(),  
355                                          std::ios::out | std::ios::binary);
356    if( !fp ) 
357    {
358       dbg.Verbose(2, "Failed to open(write) File: ", fileName.c_str());
359       return false;
360    }
361
362    char filePreamble[128];
363    memset(filePreamble, 0, 128);
364    fp->write(filePreamble, 128); //FIXME
365    binary_write( *fp, "DICM");
366  
367    DicomDirMeta *ptrMeta = GetDicomDirMeta();
368    ptrMeta->WriteContent(fp, ExplicitVR);
369    
370    // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
371    for(i=0;i<4;++i)
372    {
373       binary_write(*fp, sq[i]);
374    }
375         
376    for(ListDicomDirPatient::iterator cc  = Patients.begin();
377                                      cc != Patients.end();
378                                    ++cc )
379    {
380       (*cc)->WriteContent( fp, ExplicitVR );
381    }
382    
383    // force writing Sequence Delimitation Item
384    for(i=0;i<4;++i)
385    {
386       binary_write(*fp, sqt[i]);  // fffe e0dd ffff ffff 
387    }
388
389    fp->close();
390    delete fp;
391
392    return true;
393 }
394
395 //-----------------------------------------------------------------------------
396 // Protected
397
398 /**
399  * \ingroup DicomDir
400  * \brief create a Document-like chained list from a root Directory 
401  * @param path entry point of the tree-like structure
402  */
403 void DicomDir::CreateDicomDirChainedList(std::string const & path)
404 {
405    CallStartMethod();
406    DirList fileList(path,1); // gets recursively the file list
407    unsigned int count = 0;
408    VectDocument list;
409    Header *header;
410
411    for( DirList::iterator it  = fileList.begin();
412                               it != fileList.end();
413                               ++it )
414    {
415       Progress = (float)(count+1)/(float)fileList.size();
416       CallProgressMethod();
417       if( Abort )
418       {
419          break;
420       }
421
422 std::cerr<<"File : "<<it->c_str()<<std::endl;
423       header = new Header( it->c_str() );
424       if( !header )
425       {
426          dbg.Verbose( 1,
427                       "DicomDir::CreateDicomDirChainedList: "
428                       "failure in new Header ",
429                       it->c_str() );
430          continue;
431       }
432       
433       if( header->IsReadable() )
434       {
435          // Add the file header to the chained list:
436          list.push_back(header);
437          dbg.Verbose( 1,
438                       "DicomDir::CreateDicomDirChainedList: readable ",
439                       it->c_str() );
440        }
441        else
442        {
443           delete header;
444        }
445        count++;
446    }
447    // sorts Patient/Study/Serie/
448    std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
449    
450    std::string tmp = fileList.GetDirName();      
451    //for each Header of the chained list, add/update the Patient/Study/Serie/Image info
452    SetElements(tmp, list);
453    CallEndMethod();
454
455    for(VectDocument::iterator it=list.begin();
456        it!=list.end();
457        ++it)
458    {
459       delete dynamic_cast<Header *>(*it);
460    }
461 }
462
463 /**
464  * \ingroup DicomDir
465  * \brief   adds *the* Meta to a partially created DICOMDIR
466  */
467   
468 DicomDirMeta * DicomDir::NewMeta()
469 {
470    DicomDirMeta *m = new DicomDirMeta();
471   
472    if ( TagHT.begin() != TagHT.end() ) // after Document Parsing
473    { 
474       TagDocEntryHT::iterator lastOneButSequence = TagHT.end();
475       lastOneButSequence --;
476       // ALL the 'out of Sequence' Tags belong to Meta Elems
477       // (we skip 0004|1220 [Directory record sequence] )
478       for ( TagDocEntryHT::iterator cc  = TagHT.begin(); 
479                                     cc != lastOneButSequence;
480                                    ++cc)
481       {
482          m->AddDocEntry( cc->second );
483       }
484    }
485    else  // after root directory parsing
486    {
487       ListDicomDirMetaElem const & elemList = 
488          Global::GetDicomDirElements()->GetDicomDirMetaElements();
489       m->FillObject(elemList);
490    }
491    m->SetSQItemNumber(0); // To avoid further missprinting
492    return m;  
493 }
494
495 /**
496  * \brief   adds a new Patient (with the basic elements) to a partially created DICOMDIR
497  */
498 DicomDirPatient * DicomDir::NewPatient()
499 {
500    ListDicomDirPatientElem::const_iterator it;
501    uint16_t tmpGr,tmpEl;
502    DictEntry *dictEntry;
503    ValEntry *entry;
504
505    ListDicomDirPatientElem const & elemList =
506       Global::GetDicomDirElements()->GetDicomDirPatientElements(); 
507    DicomDirPatient *p = new DicomDirPatient();
508
509    // for all the DicomDirPatient Elements      
510    for( it = elemList.begin(); it != elemList.end(); ++it ) 
511    {
512       tmpGr     = it->Group;
513       tmpEl     = it->Elem;
514       dictEntry = GetPubDict()->GetDictEntryByNumber(tmpGr, tmpEl);
515       entry     = new ValEntry( dictEntry );
516       entry->SetOffset(0); // just to avoid further missprinting
517       entry->SetValue( it->Value );
518
519       // dealing with value length ...
520       
521       if( dictEntry->GetGroup() == 0xfffe)
522       {
523          entry->SetLength(entry->GetValue().length());
524       }
525       else if( dictEntry->GetVR() == "UL" || dictEntry->GetVR() == "SL" )
526       {
527          entry->SetLength( 4 );
528       } 
529       else if( dictEntry->GetVR() == "US" || dictEntry->GetVR() == "SS" )
530       {
531          entry->SetLength(2); 
532       } 
533       else if( dictEntry->GetVR() == "SQ" )
534       {
535          entry->SetLength( 0xffffffff );
536       }
537       else
538       {
539          entry->SetLength( entry->GetValue().length() );
540       }
541       p->AddDocEntry( entry );
542    }
543
544    Patients.push_front( p );
545
546    return p;
547 }
548
549 /**
550  * \brief   adds to the HTable 
551  *          the Entries (Dicom Elements) corresponding to the given type
552  * @param   path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
553  * @param   type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
554  *          GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
555  * @param   header Header of the current file
556  */
557 void DicomDir::SetElement(std::string const & path, DicomDirType type,
558                           Document *header)
559 {
560    ListDicomDirElem elemList; //FIXME this is going to be a by copy operation
561    ListDicomDirElem::const_iterator it;
562    uint16_t tmpGr, tmpEl;
563    DictEntry *dictEntry;
564    ValEntry *entry;
565    std::string val;
566    SQItem *si;
567
568    switch( type )
569    {
570       case GDCM_DICOMDIR_IMAGE:
571          elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
572          si = new DicomDirImage();
573          if( !AddDicomDirImageToEnd(static_cast<DicomDirImage *>(si)) )
574          {
575             dbg.Verbose(0,"DicomDir::SetElement:",
576                         "Add DicomDirImageToEnd failed");
577          }
578          break;
579       case GDCM_DICOMDIR_SERIE:
580          elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
581          si = new DicomDirSerie();
582          if( !AddDicomDirSerieToEnd(static_cast<DicomDirSerie *>(si)) )
583          {
584             dbg.Verbose(0,"DicomDir::SetElement:",
585                         "Add DicomDirSerieToEnd failed");
586          }
587          break;
588       case GDCM_DICOMDIR_STUDY:
589          elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
590          si = new DicomDirStudy();
591          if( !AddDicomDirStudyToEnd(static_cast<DicomDirStudy *>(si)) )
592          {
593             dbg.Verbose(0,"DicomDir::SetElement:",
594                         "Add DicomDirStudyToEnd failed");
595          }
596          break;
597       case GDCM_DICOMDIR_PATIENT:
598          elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
599          si = new DicomDirPatient();
600          if( !AddDicomDirPatientToEnd(static_cast<DicomDirPatient *>(si)) )
601          {
602             dbg.Verbose(0,"DicomDir::SetElement:",
603                         "Add DicomDirPatientToEnd failed");
604          }
605          break;
606       case GDCM_DICOMDIR_META:
607          elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
608          si = new DicomDirMeta();
609          if( MetaElems )
610          {
611             dbg.Verbose(0,"DicomDir::SetElement:",
612                         "MetaElements already exist, they will be destroyed");
613             delete MetaElems;
614          }
615          MetaElems = static_cast<DicomDirMeta *>(si);
616          break;
617       default:
618          return;
619    }
620    // removed all the seems-to-be-useless stuff about Referenced Image Sequence
621    // to avoid further troubles
622    // imageElem 0008 1140 "" // Referenced Image Sequence
623    // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
624    // imageElem 0008 1150 "" // Referenced SOP Class UID    : to be set/forged later
625    // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
626    // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
627    // for all the relevant elements found in their own spot of the DicomDir.dic
628    // FIXME : troubles found when it's a SeqEntry
629
630    for( it = elemList.begin(); it != elemList.end(); ++it)
631    {
632       tmpGr     = it->Group;
633       tmpEl     = it->Elem;
634       dictEntry = GetPubDict()->GetDictEntryByNumber(tmpGr, tmpEl);
635
636       entry     = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
637
638       entry->SetOffset(0); // just to avoid further missprinting
639       entry->SetLength(0); // just to avoid further missprinting
640
641       if( header )
642       {
643          // NULL when we Build Up (ex nihilo) a DICOMDIR
644          //   or when we add the META elems
645          val = header->GetEntryByNumber(tmpGr, tmpEl);
646       }
647       else
648       {
649          val = GDCM_UNFOUND;
650       }
651
652       if( val == GDCM_UNFOUND) 
653       {
654          if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
655          {
656            // force to the *end* File Name
657            val = Util::GetName( path );
658          }
659          else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
660          {
661             if( header->GetFileName().substr(0, path.length()) != path )
662             {
663                dbg.Verbose(0, "DicomDir::SetElement : the base path"
664                               " of file name is incorrect");
665                val = header->GetFileName();
666             }
667             else
668             {
669                val = &(header->GetFileName().c_str()[path.length()]);
670             }
671          }
672          else
673          {
674             val = it->Value;
675          }
676       }
677       else
678       {
679          if ( header->GetEntryLengthByNumber(tmpGr,tmpEl) == 0 )
680             val = it->Value;
681       }
682
683      // GDCM_UNFOUND or not !
684
685       entry->SetValue( val ); // troubles expected when vr=SQ ...
686
687       if( dictEntry )
688       {
689          if( dictEntry->GetGroup() == 0xfffe )
690          {
691             entry->SetLength( entry->GetValue().length() ); // FIXME 
692          }
693          else if( dictEntry->GetVR() == "UL" || dictEntry->GetVR() == "SL" )
694          {
695             entry->SetLength(4);
696          }
697          else if( dictEntry->GetVR() == "US" || dictEntry->GetVR() == "SS" )
698          {
699             entry->SetLength(2); 
700          }
701          else if( dictEntry->GetVR() == "SQ" )
702          {
703             entry->SetLength( 0xffffffff );
704          }
705          else
706          {
707             entry->SetLength( entry->GetValue().length() );
708          }
709       }
710
711       if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
712       {
713          std::cout << "GDCM_DICOMDIR_META ?!? should never print that" 
714                    << std::endl;
715       }
716       si->AddEntry(entry);
717    }
718 }
719
720 //-----------------------------------------------------------------------------
721 /**
722  * \brief   CallStartMethod
723  */
724 void DicomDir::CallStartMethod()
725 {
726    Progress = 0.0f;
727    Abort    = false;
728    if( StartMethod )
729    {
730       StartMethod( StartArg );
731    }
732 }
733
734 //-----------------------------------------------------------------------------
735 /**
736  * \ingroup DicomDir
737  * \brief   CallProgressMethod
738  */
739 void DicomDir::CallProgressMethod()
740 {
741    if( ProgressMethod )
742    {
743       ProgressMethod( ProgressArg );
744    }
745 }
746
747 //-----------------------------------------------------------------------------
748 /**
749  * \ingroup DicomDir
750  * \brief   CallEndMethod
751  */
752 void DicomDir::CallEndMethod()
753 {
754    Progress = 1.0f;
755    if( EndMethod )
756    {
757       EndMethod( EndArg );
758    }
759 }
760
761 //-----------------------------------------------------------------------------
762 // Private
763 /**
764  * \ingroup DicomDir
765  * \brief create a 'DicomDir' from a DICOMDIR Header 
766  */
767 void DicomDir::CreateDicomDir()
768 {
769    // The list is parsed. 
770    //  When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
771    //  1 - we save the beginning iterator
772    //  2 - we continue to parse
773    //  3 - we find an other tag
774    //       + we create the object for the precedent tag
775    //       + loop to 1 -
776
777    // Directory record sequence
778    DocEntry *e = GetDocEntryByNumber(0x0004, 0x1220);
779    if ( !e )
780    {
781       dbg.Verbose(0, "DicomDir::DicomDir : NO Directory record"
782                      " sequence (0x0004,0x1220)");
783       /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ? 
784       return;         
785    }
786    
787    SeqEntry* s = dynamic_cast<SeqEntry*>(e);
788    if ( !s )
789    {
790       dbg.Verbose(0, "DicomDir::CreateDicomDir: no SeqEntry present");
791       // useless : (0x0004,0x1220) IS a Sequence !
792       return;
793    }
794
795    DicomDirType type; // = DicomDir::GDCM_DICOMDIR_META;
796    MetaElems = NewMeta();
797
798    ListSQItem listItems = s->GetSQItems();
799    
800    DocEntry * d;
801    std::string v;
802    SQItem * si;
803    for( ListSQItem::iterator i = listItems.begin(); 
804                              i !=listItems.end(); ++i ) 
805    {
806       d = (*i)->GetDocEntryByNumber(0x0004, 0x1430); // Directory Record Type
807       if ( ValEntry* valEntry = dynamic_cast< ValEntry* >(d) )
808       {
809          v = valEntry->GetValue();
810       }
811       else
812       {
813          dbg.Verbose(0, "DicomDir::CreateDicomDir: not a ValEntry.");
814          continue;
815       }
816
817       if( v == "PATIENT " )
818       {
819          si = new DicomDirPatient();
820          AddDicomDirPatientToEnd( static_cast<DicomDirPatient *>(si) );
821          type = DicomDir::GDCM_DICOMDIR_PATIENT;
822       }
823       else if( v == "STUDY " )
824       {
825          si = new DicomDirStudy();
826          AddDicomDirStudyToEnd( static_cast<DicomDirStudy *>(si) );
827          type = DicomDir::GDCM_DICOMDIR_STUDY;
828       }
829       else if( v == "SERIES" )
830       {
831          si = new DicomDirSerie();
832          AddDicomDirSerieToEnd( static_cast<DicomDirSerie *>(si) );
833          type = DicomDir::GDCM_DICOMDIR_SERIE;
834       }
835       else if( v == "IMAGE " ) 
836       {
837          si = new DicomDirImage();
838          AddDicomDirImageToEnd( static_cast<DicomDirImage *>(si) );
839          type = DicomDir::GDCM_DICOMDIR_IMAGE;
840       }
841       else
842       {
843          // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
844          // neither an 'IMAGE' SQItem. Skip to next item.
845          continue;
846       }
847       MoveSQItem(si,*i);
848    }
849    TagHT.clear();
850 }
851
852 /**
853  * \ingroup DicomDir
854  * \brief Well ... there is only one occurence  
855  */
856 bool DicomDir::AddDicomDirMeta()
857 {
858    if( MetaElems )
859    {
860       delete MetaElems;
861    }
862    MetaElems = new DicomDirMeta();
863    return true;
864 }
865
866 /**
867  * \ingroup DicomDir
868  * \brief  AddDicomDirPatientToEnd 
869  * @param   s SQ Item to enqueue to the DicomPatient chained List
870  */
871 bool DicomDir::AddDicomDirPatientToEnd(DicomDirPatient *dd)
872 {
873    Patients.push_back(dd);
874    return true;
875 }
876
877 /**
878  * \ingroup DicomDir
879  * \brief  AddDicomDirStudyToEnd 
880  * @param   s SQ Item to enqueue to the DicomDirStudy chained List
881  */
882 bool DicomDir::AddDicomDirStudyToEnd(DicomDirStudy *dd)
883 {
884    if( Patients.size() > 0 )
885    {
886       ListDicomDirPatient::iterator itp = Patients.end();
887       itp--;
888       (*itp)->AddDicomDirStudy(dd);
889       return true;
890    }
891    return false;
892 }
893
894 /**
895  * \ingroup DicomDir
896  * \brief  AddDicomDirSerieToEnd 
897  * @param   s SQ Item to enqueue to the DicomDirSerie chained List
898  */
899 bool DicomDir::AddDicomDirSerieToEnd(DicomDirSerie *dd)
900 {
901    if( Patients.size() > 0 )
902    {
903       ListDicomDirPatient::iterator itp = Patients.end();
904       itp--;
905
906       if( (*itp)->GetDicomDirStudies().size() > 0 )
907       {
908          ListDicomDirStudy::const_iterator itst = 
909             (*itp)->GetDicomDirStudies().end();
910          itst--;
911          (*itst)->AddDicomDirSerie(dd);
912          return true;
913       }
914    }
915    return false;
916 }
917
918 /**
919  * \ingroup DicomDir
920  * \brief   AddDicomDirImageToEnd
921  * @param   s SQ Item to enqueue to the DicomDirImage chained List
922  */
923 bool DicomDir::AddDicomDirImageToEnd(DicomDirImage *dd)
924 {
925    if( Patients.size() > 0 )
926    {
927       ListDicomDirPatient::iterator itp = Patients.end();
928       itp--;
929
930       if( (*itp)->GetDicomDirStudies().size() > 0 )
931       {
932          ListDicomDirStudy::const_iterator itst = 
933             (*itp)->GetDicomDirStudies().end();
934          itst--;
935
936          if( (*itst)->GetDicomDirSeries().size() > 0 )
937          {
938             ListDicomDirSerie::const_iterator its = (*itst)->GetDicomDirSeries().end();
939             its--;
940             (*its)->AddDicomDirImage(dd);
941             return true;
942          }
943       }
944    }
945    return false;
946 }
947
948 /**
949  * \ingroup DicomDir
950  * \brief  for each Header of the chained list, add/update the Patient/Study/Serie/Image info 
951  * @param   path path of the root directory
952  * @param   list chained list of Headers
953  */
954 void DicomDir::SetElements(std::string const & path, VectDocument const &list)
955 {
956    TagHT.clear();
957    Patients.clear();
958
959    std::string patPrevName         = "", patPrevID  = "";
960    std::string studPrevInstanceUID = "", studPrevID = "";
961    std::string serPrevInstanceUID  = "", serPrevID  = "";
962
963    std::string patCurName,         patCurID;
964    std::string studCurInstanceUID, studCurID;
965    std::string serCurInstanceUID,  serCurID;
966
967    bool first = true;
968    for( VectDocument::const_iterator it = list.begin();
969                                      it != list.end(); ++it )
970    {
971       // get the current file characteristics
972       patCurName         = (*it)->GetEntryByNumber(0x0010,0x0010);
973       patCurID           = (*it)->GetEntryByNumber(0x0010,0x0011);
974       studCurInstanceUID = (*it)->GetEntryByNumber(0x0020,0x000d);
975       studCurID          = (*it)->GetEntryByNumber(0x0020,0x0010);
976       serCurInstanceUID  = (*it)->GetEntryByNumber(0x0020,0x000e);
977       serCurID           = (*it)->GetEntryByNumber(0x0020,0x0011);
978
979       if( patCurName != patPrevName || patCurID != patPrevID || first )
980       {
981          SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
982          first = true;
983       }
984
985       // if new Study Deal with 'STUDY' Elements   
986       if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID 
987          || first )
988       {
989          SetElement(path, GDCM_DICOMDIR_STUDY, *it);
990          first = true;
991       }
992
993       // if new Serie Deal with 'SERIE' Elements   
994       if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
995          || first )
996       {
997          SetElement(path, GDCM_DICOMDIR_SERIE, *it);
998          first = true;
999       }
1000       
1001       // Always Deal with 'IMAGE' Elements  
1002       SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
1003
1004       patPrevName         = patCurName;
1005       patPrevID           = patCurID;
1006       studPrevInstanceUID = studCurInstanceUID;
1007       studPrevID          = studCurID;
1008       serPrevInstanceUID  = serCurInstanceUID;
1009       serPrevID           = serCurID;
1010       first = false;
1011    }
1012 }
1013
1014 /**
1015  * \ingroup DicomDir
1016  * \brief   Move the content of the src SQItem to the dst SQItem
1017  *          Only DocEntry's are moved
1018  * 
1019  */
1020 void DicomDir::MoveSQItem(SQItem* dst,SQItem *src)
1021 {
1022    DocEntry *entry;
1023
1024    src->Initialize();
1025    entry = src->GetNextEntry();
1026    while(entry)
1027    {
1028       src->RemoveEntryNoDestroy(entry);
1029       dst->AddEntry(entry);
1030
1031       src->Initialize();
1032       entry = src->GetNextEntry();
1033    }
1034 }
1035
1036 /**
1037  * \ingroup DicomDir
1038  * \brief   compares two dgcmHeaders
1039  */
1040 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
1041 {
1042    return *header1 < *header2;
1043 }
1044 } // end namespace gdcm
1045
1046 //-----------------------------------------------------------------------------