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