]> Creatis software - gdcm.git/blob - src/gdcmDicomDir.cxx
* src/gdcmDicomDir.cxx, gdcmDocEntrySet.cxx: removed inclusion of errno.h
[gdcm.git] / src / gdcmDicomDir.cxx
1 /*=========================================================================
2   
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDicomDir.cxx,v $
5   Language:  C++
6   Date:      $Date: 2004/07/30 11:40:13 $
7   Version:   $Revision: 1.60 $
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.htm 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 <string>
20 #include <algorithm>
21 #include <sys/types.h>
22
23 #ifdef _MSC_VER 
24    #include <direct.h>
25 #else
26    #include <unistd.h>
27 #endif
28
29 #include "gdcmDicomDir.h"
30 #include "gdcmDicomDirStudy.h"
31 #include "gdcmDicomDirSerie.h"
32 #include "gdcmDicomDirImage.h"
33 #include "gdcmDirList.h"
34 #include "gdcmUtil.h"
35 #include "gdcmDebug.h"
36 #include "gdcmGlobal.h"
37 #include "gdcmHeader.h"
38 #include "gdcmSeqEntry.h"
39 #include "gdcmSQItem.h"
40 #include "gdcmValEntry.h"
41
42 //-----------------------------------------------------------------------------
43 //  For full DICOMDIR description, see:
44 //  PS 3.3-2003, pages 731-750
45 //-----------------------------------------------------------------------------
46 // Constructor / Destructor
47
48 /**
49  * \ingroup gdcmDicomDir
50  * \brief   Constructor : creates an empty gdcmDicomDir
51  * @param   exception_on_error whether we want to throw an exception or not
52  */
53 gdcmDicomDir::gdcmDicomDir(bool exception_on_error):                           
54    gdcmDocument( exception_on_error )
55
56    Initialize();
57
58    std::string pathBidon = "Bidon"; // Sorry, NULL not allowed ...
59    SetElement(pathBidon, GDCM_DICOMDIR_META, NULL); // Set the META elements
60    AddDicomDirMeta();
61 }
62
63 /**
64  * \brief Constructor Parses recursively the directory and creates the DicomDir
65  *        or uses an already built DICOMDIR, depending on 'parseDir' value.
66  * @param FileName        name 
67  *                      - of the root directory (parseDir = true)
68  *                      - of the DICOMDIR       (parseDir = false)
69  * @param parseDir boolean
70  *                      - true if user passed an entry point 
71  *                        and wants to explore recursively the directories
72  *                      - false if user passed an already built DICOMDIR file
73  *                        and wants to use it 
74  * @param exception_on_error whether we want to throw an exception or not
75  */
76 gdcmDicomDir::gdcmDicomDir(std::string const & fileName, bool parseDir,
77                            bool exception_on_error):
78    gdcmDocument( fileName, exception_on_error, true) // true : enable SeQuences
79 {
80    // que l'on ai passe un root directory ou un DICOMDIR
81    // et quelle que soit la valeur de parseDir,
82    // on a deja lance gdcmDocument 
83    Initialize();
84
85    // gdcmDocument already executed
86    // if user passed a root directory, sure we didn't get anything
87
88    if ( TagHT.begin() == TagHT.end() ) 
89    {
90       dbg.Verbose(0, "gdcmDicomDir::gdcmDicomDir : 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 = new char[1000];
97          getcwd(dummy, (size_t)1000);
98          std::cout << "Directory to parse : [" << dummy << "]" << std::endl;
99          SetFileName( dummy ); // will be converted into a string
100          delete[] dummy;       // no longer needed   
101       }
102
103       if ( parseDir )
104       {
105          dbg.Verbose(0, "gdcmDicomDir::gdcmDicomDir : 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
117    {
118       // Directory record sequence
119       gdcmDocEntry *e = GetDocEntryByNumber(0x0004, 0x1220);
120       if ( !e )
121       {
122          dbg.Verbose(0, "gdcmDicomDir::gdcmDicomDir : 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       CreateDicomDir();
128    }
129 }
130
131 /**
132  * \brief  Canonical destructor 
133  */
134 gdcmDicomDir::~gdcmDicomDir() 
135 {
136    SetStartMethod(NULL);
137    SetProgressMethod(NULL);
138    SetEndMethod(NULL);
139
140    if ( metaElems )
141    {
142       delete metaElems;
143    }
144    
145    for(ListDicomDirPatient::iterator cc = patients.begin();
146                                      cc!= patients.end();
147                                    ++cc)
148    {
149       delete *cc;
150    }
151 }
152
153 //-----------------------------------------------------------------------------
154 // Print
155 /**
156  * \brief  Canonical Printer 
157  */
158 void gdcmDicomDir::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 gdcmDocument is the one of a reasonable DicomDir,
182  *         false otherwise. 
183  */
184 bool gdcmDicomDir::IsReadable()
185 {
186    if( !gdcmDocument::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 gdcmDicomDir::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 = (gdcmDicomDirMeta *)0;   
222 }
223
224
225 /**
226  * \ingroup gdcmDicomDir
227  * \brief  fills the whole structure, starting from a root Directory
228  */
229 void gdcmDicomDir::ParseDirectory()
230 {
231    CreateDicomDirChainedList( GetFileName() );
232    CreateDicomDir();
233 }
234
235 /**
236  * \ingroup gdcmDicomDir
237  * \brief   Set the start method to call when the parsing of the directory starts
238  * @param   method Method to call
239  * @param   arg    Argument to pass to the method
240  * @param   argDelete    Argument 
241  * \warning In python : the arg parameter isn't considered
242  */
243 void gdcmDicomDir::SetStartMethod(gdcmMethod *method, void *arg, 
244                                   gdcmMethod *argDelete )
245 {
246    if( startArg && startMethodArgDelete )
247    {
248       startMethodArgDelete( startArg );
249    }
250
251    startMethod          = method;
252    startArg             = arg;
253    startMethodArgDelete = argDelete;
254 }
255
256 /**
257  * \ingroup gdcmDicomDir
258  * \brief   Set the method to delete the argument
259  *          The argument is destroyed when the method is changed or when the
260  *          class is destroyed
261  * @param   method Method to call to delete the argument
262  */
263 void gdcmDicomDir::SetStartMethodArgDelete(gdcmMethod *method) 
264 {
265    startMethodArgDelete = method;
266 }
267
268 /**
269  * \ingroup gdcmDicomDir
270  * \brief   Set the progress method to call when the parsing of the directory progress
271  * @param   method Method to call
272  * @param   arg    Argument to pass to the method
273  * @param   argDelete    Argument  
274  * \warning In python : the arg parameter isn't considered
275  */
276 void gdcmDicomDir::SetProgressMethod(gdcmMethod *method, void *arg, 
277                                      gdcmMethod *argDelete )
278 {
279    if( progressArg && progressMethodArgDelete )
280    {
281       progressMethodArgDelete( progressArg );
282    }
283
284    progressMethod          = method;
285    progressArg             = arg;
286    progressMethodArgDelete = argDelete;
287 }
288
289 /**
290  * \ingroup gdcmDicomDir
291  * \brief   Set the method to delete the argument
292  *          The argument is destroyed when the method is changed or when the 
293  *          class is destroyed          
294  * @param   method Method to call to delete the argument
295  */
296 void gdcmDicomDir::SetProgressMethodArgDelete(gdcmMethod *method)
297 {
298    progressMethodArgDelete = method;
299 }
300
301 /**
302  * \ingroup gdcmDicomDir
303  * \brief   Set the end method to call when the parsing of the directory ends
304  * @param   method Method to call
305  * @param   arg    Argument to pass to the method
306  * @param   argDelete    Argument 
307  * \warning In python : the arg parameter isn't considered
308  */
309 void gdcmDicomDir::SetEndMethod(gdcmMethod *method, void *arg, 
310                                 gdcmMethod *argDelete )
311 {
312    if( endArg && endMethodArgDelete )
313    {
314       endMethodArgDelete( endArg );
315    }
316
317    endMethod          = method;
318    endArg             = arg;
319    endMethodArgDelete = argDelete;
320 }
321
322 /**
323  * \ingroup gdcmDicomDir
324  * \brief   Set the method to delete the argument
325  *          The argument is destroyed when the method is changed or when the class
326  *          is destroyed
327  * @param   method Method to call to delete the argument
328  */
329 void gdcmDicomDir::SetEndMethodArgDelete(gdcmMethod *method)
330 {
331    endMethodArgDelete = method;
332 }
333
334 /**
335  * \ingroup gdcmDicomDir
336  * \brief   writes on disc a DICOMDIR
337  * \ warning does NOT add the missing elements in the header :
338  *           it's up to the user doing it !
339  * \todo : to be re-written using the DICOMDIR tree-like structure
340  *         *not* the chained list
341  *         (does NOT exist if the DICOMDIR is user-forged !)
342  * @param  fileName file to be written to 
343  * @return false only when fail to open
344  */
345  
346 bool gdcmDicomDir::Write(std::string const & fileName) 
347 {
348    FILE * fp1;
349
350    fp1 = fopen(fileName.c_str(), "wb");
351    if( !fp1 ) 
352    {
353       printf("Failed to open(write) File [%s] \n", fileName.c_str());
354       return false;
355    }
356
357    char * filePreamble = new char[128];
358    fwrite(filePreamble,128,1,fp1);
359    fwrite("DICM",4,1,fp1);
360    delete[] filePreamble;
361    UpdateDirectoryRecordSequenceLength();
362    WriteEntries(fp1);
363
364    fclose( fp1 );
365    return true;
366 }
367
368 /**
369  * \brief   Writes in a file using the tree-like structure.
370  * @param   _fp already open file pointer
371  */
372
373 void gdcmDicomDir::WriteEntries(FILE *) //_fp
374 {   
375    /// \todo (?) tester les echecs en ecriture 
376    ///          (apres chaque fwrite, dans le WriteEntry)
377
378
379 /* TODO : to go on compiling
380
381    gdcmDicomDirMeta *ptrMeta;
382    ListDicomDirPatient::iterator  itPatient;
383    ListDicomDirStudy::iterator    itStudy;
384    ListDicomDirSerie::iterator    itSerie;
385    ListDicomDirImage::iterator    itImage; 
386    ListTag::iterator i; 
387    
388    ptrMeta= GetDicomDirMeta();
389    for(i=ptrMeta->debut();i!=ptrMeta->fin();++i) {
390       WriteEntry(*i,_fp, gdcmExplicitVR);
391    }   
392     
393    itPatient = GetDicomDirPatients().begin(); 
394    while ( itPatient != GetDicomDirPatients().end() ) {
395       for(i=(*itPatient)->debut();i!=(*itPatient)->fin();++i) {
396          WriteEntry(*i,_fp, gdcmExplicitVR);
397       }
398       itStudy = ((*itPatient)->GetDicomDirStudies()).begin();     
399       while (itStudy != (*itPatient)->GetDicomDirStudies().end() ) {
400          for(i=(*itStudy)->debut();i!=(*itStudy)->fin();++i) {
401             WriteEntry(*i,_fp, gdcmExplicitVR);
402          } 
403          itSerie = ((*itStudy)->GetDicomDirSeries()).begin();
404          while (itSerie != (*itStudy)->GetDicomDirSeries().end() ) {
405             for(i=(*itSerie)->debut();i!=(*itSerie)->fin();++i) {
406                WriteEntry(*i,_fp, gdcmExplicitVR);
407             }
408             itImage = ((*itSerie)->GetDicomDirImages()).begin();
409             while (itImage != (*itSerie)->GetDicomDirImages().end() ) {
410                for(i=(*itImage)->debut();i!=(*itImage)->fin();++i) {
411                   WriteEntry(*i,_fp, gdcmExplicitVR);
412                }
413                ++itImage;
414             }
415             ++itSerie;
416          }
417          ++itStudy;
418       } 
419       ++itPatient;     
420    }
421    */
422 }   
423    
424 //-----------------------------------------------------------------------------
425 // Protected
426
427 /**
428  * \ingroup gdcmDicomDir
429  * \brief create a gdcmDocument-like chained list from a root Directory 
430  * @param path entry point of the tree-like structure
431  */
432 void gdcmDicomDir::CreateDicomDirChainedList(std::string const & path)
433 {
434    CallStartMethod();
435    gdcmDirList fileList(path,1); // gets recursively the file list
436    unsigned int count = 0;
437    VectDocument list;
438    gdcmHeader *header;
439
440    TagHT.clear();
441    patients.clear();
442
443    for( gdcmDirList::iterator it  = fileList.begin();
444                               it != fileList.end();
445                               ++it )
446    {
447       progress = (float)(count+1)/(float)fileList.size();
448       CallProgressMethod();
449       if( abort )
450       {
451          break;
452       }
453
454       header = new gdcmHeader(it->c_str(),false,true);
455       if(!header) {
456          std::cout << "failure in new Header " << it->c_str() << std::endl; // JPR
457       }
458       if(header->IsReadable()) {
459          list.push_back(header);  // adds the file header to the chained list
460          std::cout << "readable : " <<it->c_str() << std::endl; // JPR
461        }
462       else
463       {
464          delete header;
465       }
466       count++;
467
468    }
469    // sorts Patient/Study/Serie/
470    std::sort(list.begin(), list.end(), gdcmDicomDir::HeaderLessThan );
471
472    std::string tmp = fileList.GetDirName();
473       
474    //for each Header of the chained list, add/update the Patient/Study/Serie/Image info
475    SetElements(tmp, list);
476       
477    CallEndMethod();
478 }
479
480 /**
481  * \ingroup gdcmDicomDir
482  * \brief   adds *the* Meta to a partially created DICOMDIR
483  */
484  
485  /// \todo FIXME : Heuuuuu ! Il prend les Entries du Document deja parse,
486  ///                  il ne fabrique rien !
487   
488 gdcmDicomDirMeta * gdcmDicomDir::NewMeta()
489 {
490    gdcmDicomDirMeta *m = new gdcmDicomDirMeta( &TagHT );
491    for ( TagDocEntryHT::iterator cc  = TagHT.begin(); 
492                                  cc != TagHT.end(); ++cc)
493    {
494       m->AddDocEntry( cc->second );
495    }
496    return m;  
497 }
498
499
500 /**
501  * \brief   adds a new Patient (with the basic elements) to a partially created DICOMDIR
502  */
503 gdcmDicomDirPatient * gdcmDicomDir::NewPatient()
504 {
505    std::list<gdcmElement>::iterator it;
506    uint16_t tmpGr,tmpEl;
507    gdcmDictEntry *dictEntry;
508    gdcmValEntry *entry;
509
510    std::list<gdcmElement> elemList;   
511    elemList=gdcmGlobal::GetDicomDirElements()->GetDicomDirPatientElements(); 
512 // Looks nice, but gdcmDicomDir IS NOT a gdcmObject ... 
513 //   gdcmDicomDirPatient *p = new gdcmDicomDirPatient(ptagHT);
514 //   FillObject(elemList);
515 //   patients.push_front( p );
516 //   return p;    
517 /// \todo TODO : find a trick to use FillObject !!!
518
519    gdcmSQItem *s = new gdcmSQItem(0);
520
521    // for all the DicomDirPatient Elements      
522    for( it = elemList.begin(); it != elemList.end(); ++it ) 
523    {
524       tmpGr     = it->group;
525       tmpEl     = it->elem;
526       dictEntry = GetPubDict()->GetDictEntryByNumber(tmpGr, tmpEl);
527       entry     = new gdcmValEntry( dictEntry );
528       entry->SetOffset(0); // just to avoid further missprinting
529       entry->SetValue( it->value );
530
531       // dealing with value length ...
532       
533       if( dictEntry->GetGroup() == 0xfffe)
534       {
535          entry->SetLength(entry->GetValue().length());
536       }
537       else if( dictEntry->GetVR() == "UL" || dictEntry->GetVR() == "SL" )
538       {
539          entry->SetLength( 4 );
540       } 
541       else if( dictEntry->GetVR() == "US" || dictEntry->GetVR() == "SS" )
542       {
543          entry->SetLength(2); 
544       } 
545       else if( dictEntry->GetVR() == "SQ" )
546       {
547          entry->SetLength( 0xffffffff );
548       }
549       else
550       {
551          entry->SetLength( entry->GetValue().length() );
552       }
553       s->AddDocEntry( entry );
554    }
555
556    gdcmDicomDirPatient *p = new gdcmDicomDirPatient(s, &TagHT);
557    patients.push_front( p );
558
559    return p;   
560 }
561
562 /**
563  * \brief   adds to the HTable 
564  *          the gdcmEntries (Dicom Elements) corresponding to the given type
565  * @param   path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
566  * @param   type gdcmObject type to create (GDCM_DICOMDIR_PATIENT,
567  *          GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
568  * @param   header gdcmHeader of the current file
569  */
570 void gdcmDicomDir::SetElement(std::string &path,gdcmDicomDirType type,
571                               gdcmDocument *header)
572 {
573    std::list<gdcmElement> elemList;
574    std::list<gdcmElement>::iterator it;
575    uint16_t tmpGr, tmpEl;
576    gdcmDictEntry *dictEntry;
577    gdcmValEntry *entry;
578    std::string val;
579    //gdcmObject *o;
580    switch( type )
581    {
582       case GDCM_DICOMDIR_IMAGE:
583          elemList = gdcmGlobal::GetDicomDirElements()->GetDicomDirImageElements();
584          break;
585
586       case GDCM_DICOMDIR_SERIE:
587          elemList = gdcmGlobal::GetDicomDirElements()->GetDicomDirSerieElements();
588          break;
589
590       case GDCM_DICOMDIR_STUDY:
591          elemList = gdcmGlobal::GetDicomDirElements()->GetDicomDirStudyElements();
592          break;
593
594       case GDCM_DICOMDIR_PATIENT:
595          elemList = gdcmGlobal::GetDicomDirElements()->GetDicomDirPatientElements();
596          break;
597   
598       case GDCM_DICOMDIR_META:
599          elemList = gdcmGlobal::GetDicomDirElements()->GetDicomDirMetaElements();
600          break;
601
602       default:
603          return;
604    }
605
606    for( it = elemList.begin(); it != elemList.end(); ++it)
607    {
608       tmpGr     = it->group;
609       tmpEl     = it->elem;
610       dictEntry = GetPubDict()->GetDictEntryByNumber(tmpGr, tmpEl);
611       entry     = new gdcmValEntry( dictEntry ); // Be sure it's never a BinEntry !
612
613       entry->SetOffset(0); // just to avoid further missprinting
614
615       if( header ) // NULL when we Build Up (ex nihilo) a DICOMDIR
616                    //   or when we add the META elems
617       {
618          val = header->GetEntryByNumber(tmpGr, tmpEl);
619       }
620       else
621       {
622          val = GDCM_UNFOUND;
623       }
624
625       if( val == GDCM_UNFOUND) 
626       {
627          if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
628          {
629            // force to the *end* File Name
630            val = GetName( path );
631          }
632          else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
633          {
634             if( header->GetFileName().substr(0, path.length()) != path )
635             {
636                dbg.Verbose(0, "gdcmDicomDir::SetElement : the base path"
637                               " of file name is incorrect");
638                val = header->GetFileName();
639             }
640             else
641             {
642                val = &(header->GetFileName().c_str()[path.length()]);
643             }   
644          }
645          else
646          {
647             val = it->value;
648          }
649       }
650       else
651       {
652          if ( header->GetEntryLengthByNumber(tmpGr,tmpEl) == 0 )
653          {
654             val = it->value;
655          }
656       }
657
658       entry->SetValue( val );
659
660       if( dictEntry )
661       {
662          if( dictEntry->GetGroup() == 0xfffe )
663          {
664             entry->SetLength( entry->GetValue().length() ); // FIXME 
665          }
666          else if( dictEntry->GetVR() == "UL" || dictEntry->GetVR() == "SL" )
667          {
668             entry->SetLength(4);
669          }
670          else if( dictEntry->GetVR() == "US" || dictEntry->GetVR() == "SS" )
671          {
672             entry->SetLength(2); 
673          }
674          else if( dictEntry->GetVR() == "SQ" )
675          {
676             entry->SetLength( 0xffffffff );
677          }
678          else
679          {
680             entry->SetLength( entry->GetValue().length() );
681          }
682       }
683       std::cout << " was TagHT[entry->GetKey()] = entry " << std::endl;
684       if ( type == GDCM_DICOMDIR_META ) {
685          std::cout << " special Treatment for GDCM_DICOMDIR_META" << std::endl;
686          
687       }
688       //TagHT[entry->GetKey()] = entry;          // FIXME : use a SEQUENCE !
689    }
690 }
691
692 /**
693  * \brief   CallStartMethod
694  */
695 void gdcmDicomDir::CallStartMethod()
696 {
697    progress = 0.0f;
698    abort    = false;
699    if( startMethod )
700    {
701       startMethod( startArg );
702    }
703 }
704
705 /**
706  * \ingroup gdcmDicomDir
707  * \brief   CallProgressMethod
708  */
709 void gdcmDicomDir::CallProgressMethod()
710 {
711    if( progressMethod )
712    {
713       progressMethod( progressArg );
714    }
715 }
716
717 /**
718  * \ingroup gdcmDicomDir
719  * \brief   CallEndMethod
720  */
721 void gdcmDicomDir::CallEndMethod()
722 {
723    progress = 1.0f;
724    if( endMethod )
725    {
726       endMethod( endArg );
727    }
728 }
729
730 //-----------------------------------------------------------------------------
731 // Private
732 /**
733  * \ingroup gdcmDicomDir
734  * \brief create a 'gdcmDicomDir' from a DICOMDIR gdcmHeader 
735  */
736 void gdcmDicomDir::CreateDicomDir()
737 {
738    // The list is parsed. 
739    //  When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
740    //  1 - we save the beginning iterator
741    //  2 - we continue to parse
742    //  3 - we find an other tag
743    //       + we create the object for the precedent tag
744    //       + loop to 1 -
745
746    // Directory record sequence
747    gdcmDocEntry *e = GetDocEntryByNumber(0x0004, 0x1220);
748    if ( !e )
749    {
750       dbg.Verbose(0, "gdcmDicomDir::gdcmDicomDir : NO Directory record"
751                      " sequence (0x0004,0x1220)");
752       /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ? 
753       return;         
754    }
755    
756    gdcmSeqEntry* s = dynamic_cast<gdcmSeqEntry*>(e);
757    if ( !s )
758    {
759       dbg.Verbose(0, "gdcmDicomDir::CreateDicomDir: no SeqEntry present");
760       // useless : (0x0004,0x1220) IS a Sequence !
761       return;
762    }
763
764    gdcmDicomDirType type = gdcmDicomDir::GDCM_DICOMDIR_META;
765    metaElems = NewMeta();
766
767    ListSQItem listItems = s->GetSQItems();
768    
769    gdcmDocEntry * d;
770    std::string v;
771    for( ListSQItem::iterator i = listItems.begin(); 
772                              i !=listItems.end(); ++i ) 
773    {
774       d = (*i)->GetDocEntryByNumber(0x0004, 0x1430); // Directory Record Type
775       if ( gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(d) )
776       {
777          v = ValEntry->GetValue();
778       }
779       else
780       {
781          dbg.Verbose(0, "gdcmDicomDir::CreateDicomDir: not a ValEntry.");
782          continue;
783       }
784
785       if( v == "PATIENT " )
786       {
787          AddDicomDirPatientToEnd( *i );
788          //AddObjectToEnd(type,*i);
789          type = gdcmDicomDir::GDCM_DICOMDIR_PATIENT;
790       }
791       else if( v == "STUDY " )
792       {
793          AddDicomDirStudyToEnd( *i );
794         // AddObjectToEnd(type,*i);
795          type = gdcmDicomDir::GDCM_DICOMDIR_STUDY;
796       }
797       else if( v == "SERIES" )
798       {
799          AddDicomDirSerieToEnd( *i );
800          //  AddObjectToEnd(type,*i);
801          type = gdcmDicomDir::GDCM_DICOMDIR_SERIE;
802       }
803       else if( v == "IMAGE " ) 
804       {
805          AddDicomDirImageToEnd( *i );
806          //   AddObjectToEnd(type,*i);
807          type = gdcmDicomDir::GDCM_DICOMDIR_IMAGE;
808       }
809       else
810       {
811          // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
812          // neither an 'IMAGE' SQItem. Skip to next item.
813          continue;
814       }
815    }
816 }
817
818 /**
819  * \ingroup gdcmDicomDir
820  * \brief   AddObjectToEnd
821  * @param   type
822  * @param   begin iterator on the first DocEntry within the chained List
823  * @param   end iterator on the last DocEntry within the chained List
824  */
825  
826 // now  useless ?
827
828 /*void gdcmDicomDir::AddObjectToEnd(gdcmDicomDirType type,gdcmSQItem *s)
829 {
830    if(s==NULL) // ??
831       return;
832
833    switch(type)
834    {
835       case gdcmDicomDir::GDCM_DICOMDIR_META:
836          AddDicomDirMeta();
837          break;      
838       case gdcmDicomDir::GDCM_DICOMDIR_PATIENT:
839          AddDicomDirPatientToEnd(s);
840          break;
841       case gdcmDicomDir::GDCM_DICOMDIR_STUDY:
842          AddDicomDirStudyToEnd(s);
843          break;
844       case gdcmDicomDir::GDCM_DICOMDIR_SERIE:
845          AddDicomDirSerieToEnd(s);
846          break;
847       case gdcmDicomDir::GDCM_DICOMDIR_IMAGE:
848          AddDicomDirImageToEnd(s);
849          break;
850       case gdcmDicomDir::GDCM_DICOMDIR_NONE:
851          AddDicomDirImageToEnd(s);        //FIXME
852          break;
853    }
854 }
855
856 */
857
858 /**
859  * \ingroup gdcmDicomDir
860  * \brief Well ... there is only one occurence  
861  */
862 void gdcmDicomDir::AddDicomDirMeta()
863 {
864    if( metaElems )
865    {
866       delete metaElems;
867    }
868    metaElems = new gdcmDicomDirMeta( &TagHT );
869 }
870
871 /**
872  * \ingroup gdcmDicomDir
873  * \brief  AddDicomDirPatientToEnd 
874  * @param   s SQ Item to enqueue to the DicomPatient chained List
875  */
876 void gdcmDicomDir::AddDicomDirPatientToEnd(gdcmSQItem *s)
877 {
878    patients.push_back(new gdcmDicomDirPatient(s, &TagHT));
879 }
880
881 /**
882  * \ingroup gdcmDicomDir
883  * \brief  AddDicomDirStudyToEnd 
884  * @param   s SQ Item to enqueue to the DicomDirStudy chained List
885  */
886  void gdcmDicomDir::AddDicomDirStudyToEnd(gdcmSQItem *s)
887 {
888    if( patients.size() > 0 )
889    {
890       ListDicomDirPatient::iterator itp = patients.end();
891       itp--;
892       (*itp)->AddDicomDirStudy(new gdcmDicomDirStudy(s, &TagHT));
893    }
894 }
895
896 /**
897  * \ingroup gdcmDicomDir
898  * \brief  AddDicomDirSerieToEnd 
899  * @param   s SQ Item to enqueue to the DicomDirSerie chained List
900  */
901 void gdcmDicomDir::AddDicomDirSerieToEnd(gdcmSQItem *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::iterator itst=(*itp)->GetDicomDirStudies().end();
911          itst--;
912          (*itst)->AddDicomDirSerie(new gdcmDicomDirSerie(s, &TagHT));
913       }
914    }
915 }
916
917 /**
918  * \ingroup gdcmDicomDir
919  * \brief   AddDicomDirImageToEnd
920  * @param   s SQ Item to enqueue to the DicomDirImage chained List
921  */
922  void gdcmDicomDir::AddDicomDirImageToEnd(gdcmSQItem *s)
923 {
924    if( patients.size() > 0 )
925    {
926       ListDicomDirPatient::iterator itp = patients.end();
927       itp--;
928
929       if( (*itp)->GetDicomDirStudies().size() > 0 )
930       {
931          ListDicomDirStudy::iterator itst = (*itp)->GetDicomDirStudies().end();
932          itst--;
933
934          if( (*itst)->GetDicomDirSeries().size() > 0 )
935          {
936             ListDicomDirSerie::iterator its = (*itst)->GetDicomDirSeries().end();
937             its--;
938             (*its)->AddDicomDirImage(new gdcmDicomDirImage(s, &TagHT));
939          }
940       }
941    }
942 }
943
944 /**
945  * \ingroup gdcmDicomDir
946  * \brief  for each Header of the chained list, add/update the Patient/Study/Serie/Image info 
947  * @param   path path of the root directory
948  * @param   list chained list of Headers
949  */
950 void gdcmDicomDir::SetElements(std::string &path, VectDocument &list)
951 {
952    std::string patPrevName         = "", patPrevID  = "";
953    std::string studPrevInstanceUID = "", studPrevID = "";
954    std::string serPrevInstanceUID  = "", serPrevID  = "";
955
956    std::string patCurName,         patCurID;
957    std::string studCurInstanceUID, studCurID;
958    std::string serCurInstanceUID,  serCurID;
959
960    SetElement( path, GDCM_DICOMDIR_META,NULL);
961
962    for( VectDocument::iterator it = list.begin();
963                               it != list.end(); ++it )
964    {
965       // get the current file characteristics
966       patCurName         = (*it)->GetEntryByNumber(0x0010,0x0010); 
967       patCurID           = (*it)->GetEntryByNumber(0x0010,0x0011); 
968       studCurInstanceUID = (*it)->GetEntryByNumber(0x0020,0x000d);            
969       studCurID          = (*it)->GetEntryByNumber(0x0020,0x0010);            
970       serCurInstanceUID  = (*it)->GetEntryByNumber(0x0020,0x000e);            
971       serCurID           = (*it)->GetEntryByNumber(0x0020,0x0011);
972
973       if( patCurName != patPrevName || patCurID != patPrevID)
974       {
975          SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
976       }
977
978       // if new Study Deal with 'STUDY' Elements   
979       if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID )
980       {
981          SetElement(path, GDCM_DICOMDIR_STUDY, *it);
982       }
983
984       // if new Serie Deal with 'SERIE' Elements   
985       if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID )
986       {
987          SetElement(path, GDCM_DICOMDIR_SERIE, *it);
988       }
989       
990       // Always Deal with 'IMAGE' Elements  
991       SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
992
993       patPrevName         = patCurName;
994       patPrevID           = patCurID;
995       studPrevInstanceUID = studCurInstanceUID;
996       studPrevID          = studCurID;
997       serPrevInstanceUID  = serCurInstanceUID;
998       serPrevID           = serCurID;
999    }
1000 }
1001
1002 /**
1003  * \ingroup gdcmDicomDir
1004  * \brief   compares two dgcmHeaders
1005  */
1006 bool gdcmDicomDir::HeaderLessThan(gdcmDocument *header1, gdcmDocument *header2)
1007 {
1008    return *header1 < *header2;
1009 }
1010
1011 /**
1012  * \brief   Sets the accurate value for the (0x0004,0x1220) element of a DICOMDIR
1013  */
1014 void gdcmDicomDir::UpdateDirectoryRecordSequenceLength()
1015 {
1016
1017 /// \todo FIXME : to go on compiling
1018 ///
1019 /// to be re written !
1020 ///   int offset = 0;
1021 ///   ListTag::iterator it;
1022 ///   uint16_t gr, el;
1023 ///   std::string vr;
1024 ///   for(it=listEntries.begin();it!=listEntries.end();++it) {
1025 ///      gr = (*it)->GetGroup();
1026 ///      el = (*it)->GetElement();
1027 ///      vr = (*it)->GetVR();      
1028 ///      if (gr !=0xfffe) {
1029 ///         if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ) {    
1030 ///            offset +=  4; // explicit VR AND OB, OW, SQ : 4 more bytes
1031 ///         }         
1032 ///         offset += 2 + 2 + 4 + (*it)->GetLength(); 
1033 ///      } else {
1034 ///         offset +=  4; // delimiters don't have a value.     
1035 ///      }            
1036 ///   }   
1037 ///   //bool res=SetEntryLengthByNumber(offset, 0x0004, 0x1220); // Hope there is no dupps.
1038 ///    SetEntryLengthByNumber(offset, 0x0004, 0x1220); // Hope there is no dupps.
1039 ///   return;
1040 ///
1041 }
1042
1043 //-----------------------------------------------------------------------------