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