]> Creatis software - gdcm.git/blob - src/gdcmDicomDir.cxx
ENH: Guess what ! Still some cosmetic cleanup
[gdcm.git] / src / gdcmDicomDir.cxx
1 /*=========================================================================
2   
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDicomDir.cxx,v $
5   Language:  C++
6   Date:      $Date: 2004/08/01 02:39:09 $
7   Version:   $Revision: 1.62 $
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)
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 = 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 = fopen(fileName.c_str(), "wb");
349    if( !fp1 ) 
350    {
351       printf("Failed to open(write) File [%s] \n", fileName.c_str());
352       return false;
353    }
354
355    char * filePreamble = new char[128];
356    fwrite(filePreamble,128,1,fp1);
357    fwrite("DICM",4,1,fp1);
358    delete[] filePreamble;
359    UpdateDirectoryRecordSequenceLength();
360    WriteEntries(fp1);
361
362    fclose( fp1 );
363    return true;
364 }
365
366 /**
367  * \brief   Writes in a file using the tree-like structure.
368  * @param   _fp already open file pointer
369  */
370
371 void gdcmDicomDir::WriteEntries(FILE *) //_fp
372 {   
373    /// \todo (?) tester les echecs en ecriture 
374    ///          (apres chaque fwrite, dans le WriteEntry)
375
376
377 /* TODO : to go on compiling
378
379    gdcmDicomDirMeta *ptrMeta;
380    ListDicomDirPatient::iterator  itPatient;
381    ListDicomDirStudy::iterator    itStudy;
382    ListDicomDirSerie::iterator    itSerie;
383    ListDicomDirImage::iterator    itImage; 
384    ListTag::iterator i; 
385    
386    ptrMeta= GetDicomDirMeta();
387    for(i=ptrMeta->debut();i!=ptrMeta->fin();++i) {
388       WriteEntry(*i,_fp, gdcmExplicitVR);
389    }   
390     
391    itPatient = GetDicomDirPatients().begin(); 
392    while ( itPatient != GetDicomDirPatients().end() ) {
393       for(i=(*itPatient)->debut();i!=(*itPatient)->fin();++i) {
394          WriteEntry(*i,_fp, gdcmExplicitVR);
395       }
396       itStudy = ((*itPatient)->GetDicomDirStudies()).begin();     
397       while (itStudy != (*itPatient)->GetDicomDirStudies().end() ) {
398          for(i=(*itStudy)->debut();i!=(*itStudy)->fin();++i) {
399             WriteEntry(*i,_fp, gdcmExplicitVR);
400          } 
401          itSerie = ((*itStudy)->GetDicomDirSeries()).begin();
402          while (itSerie != (*itStudy)->GetDicomDirSeries().end() ) {
403             for(i=(*itSerie)->debut();i!=(*itSerie)->fin();++i) {
404                WriteEntry(*i,_fp, gdcmExplicitVR);
405             }
406             itImage = ((*itSerie)->GetDicomDirImages()).begin();
407             while (itImage != (*itSerie)->GetDicomDirImages().end() ) {
408                for(i=(*itImage)->debut();i!=(*itImage)->fin();++i) {
409                   WriteEntry(*i,_fp, gdcmExplicitVR);
410                }
411                ++itImage;
412             }
413             ++itSerie;
414          }
415          ++itStudy;
416       } 
417       ++itPatient;     
418    }
419    */
420 }   
421    
422 //-----------------------------------------------------------------------------
423 // Protected
424
425 /**
426  * \ingroup gdcmDicomDir
427  * \brief create a gdcmDocument-like chained list from a root Directory 
428  * @param path entry point of the tree-like structure
429  */
430 void gdcmDicomDir::CreateDicomDirChainedList(std::string const & path)
431 {
432    CallStartMethod();
433    gdcmDirList fileList(path,1); // gets recursively the file list
434    unsigned int count = 0;
435    VectDocument list;
436    gdcmHeader *header;
437
438    TagHT.clear();
439    patients.clear();
440
441    for( gdcmDirList::iterator it  = fileList.begin();
442                               it != fileList.end();
443                               ++it )
444    {
445       progress = (float)(count+1)/(float)fileList.size();
446       CallProgressMethod();
447       if( abort )
448       {
449          break;
450       }
451
452       header = new gdcmHeader( it->c_str(),false );
453       if( !header )
454       {
455          dbg.Verbose( 1,
456                       "gdcmDicomDir::CreateDicomDirChainedList: "
457                       "failure in new Header ",
458                       it->c_str() );
459       }
460       if( header->IsReadable() )
461       {
462          // Add the file header to the chained list:
463          list.push_back(header);
464          dbg.Verbose( 1,
465                       "gdcmDicomDir::CreateDicomDirChainedList: readable ",
466                       it->c_str() );
467        }
468        else
469        {
470           delete header;
471        }
472        count++;
473    }
474
475    // sorts Patient/Study/Serie/
476    std::sort(list.begin(), list.end(), gdcmDicomDir::HeaderLessThan );
477
478    std::string tmp = fileList.GetDirName();
479       
480    //for each Header of the chained list, add/update the Patient/Study/Serie/Image info
481    SetElements(tmp, list);
482       
483    CallEndMethod();
484 }
485
486 /**
487  * \ingroup gdcmDicomDir
488  * \brief   adds *the* Meta to a partially created DICOMDIR
489  */
490  
491  /// \todo FIXME : Heuuuuu ! Il prend les Entries du Document deja parse,
492  ///                  il ne fabrique rien !
493   
494 gdcmDicomDirMeta * gdcmDicomDir::NewMeta()
495 {
496    gdcmDicomDirMeta *m = new gdcmDicomDirMeta( &TagHT );
497    for ( TagDocEntryHT::iterator cc  = TagHT.begin(); 
498                                  cc != TagHT.end(); ++cc)
499    {
500       m->AddDocEntry( cc->second );
501    }
502    return m;  
503 }
504
505
506 /**
507  * \brief   adds a new Patient (with the basic elements) to a partially created DICOMDIR
508  */
509 gdcmDicomDirPatient * gdcmDicomDir::NewPatient()
510 {
511    std::list<gdcmElement>::iterator it;
512    uint16_t tmpGr,tmpEl;
513    gdcmDictEntry *dictEntry;
514    gdcmValEntry *entry;
515
516    std::list<gdcmElement> elemList;   
517    elemList=gdcmGlobal::GetDicomDirElements()->GetDicomDirPatientElements(); 
518 // Looks nice, but gdcmDicomDir IS NOT a gdcmObject ... 
519 //   gdcmDicomDirPatient *p = new gdcmDicomDirPatient(ptagHT);
520 //   FillObject(elemList);
521 //   patients.push_front( p );
522 //   return p;    
523 /// \todo TODO : find a trick to use FillObject !!!
524
525    gdcmSQItem *s = new gdcmSQItem(0);
526
527    // for all the DicomDirPatient Elements      
528    for( it = elemList.begin(); it != elemList.end(); ++it ) 
529    {
530       tmpGr     = it->group;
531       tmpEl     = it->elem;
532       dictEntry = GetPubDict()->GetDictEntryByNumber(tmpGr, tmpEl);
533       entry     = new gdcmValEntry( dictEntry );
534       entry->SetOffset(0); // just to avoid further missprinting
535       entry->SetValue( it->value );
536
537       // dealing with value length ...
538       
539       if( dictEntry->GetGroup() == 0xfffe)
540       {
541          entry->SetLength(entry->GetValue().length());
542       }
543       else if( dictEntry->GetVR() == "UL" || dictEntry->GetVR() == "SL" )
544       {
545          entry->SetLength( 4 );
546       } 
547       else if( dictEntry->GetVR() == "US" || dictEntry->GetVR() == "SS" )
548       {
549          entry->SetLength(2); 
550       } 
551       else if( dictEntry->GetVR() == "SQ" )
552       {
553          entry->SetLength( 0xffffffff );
554       }
555       else
556       {
557          entry->SetLength( entry->GetValue().length() );
558       }
559       s->AddDocEntry( entry );
560    }
561
562    gdcmDicomDirPatient *p = new gdcmDicomDirPatient(s, &TagHT);
563    patients.push_front( p );
564
565    return p;   
566 }
567
568 /**
569  * \brief   adds to the HTable 
570  *          the gdcmEntries (Dicom Elements) corresponding to the given type
571  * @param   path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
572  * @param   type gdcmObject type to create (GDCM_DICOMDIR_PATIENT,
573  *          GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
574  * @param   header gdcmHeader of the current file
575  */
576 void gdcmDicomDir::SetElement(std::string &path,gdcmDicomDirType type,
577                               gdcmDocument *header)
578 {
579    std::list<gdcmElement> elemList;
580    std::list<gdcmElement>::iterator it;
581    uint16_t tmpGr, tmpEl;
582    gdcmDictEntry *dictEntry;
583    gdcmValEntry *entry;
584    std::string val;
585    //gdcmObject *o;
586    switch( type )
587    {
588       case GDCM_DICOMDIR_IMAGE:
589          elemList = gdcmGlobal::GetDicomDirElements()->GetDicomDirImageElements();
590          break;
591
592       case GDCM_DICOMDIR_SERIE:
593          elemList = gdcmGlobal::GetDicomDirElements()->GetDicomDirSerieElements();
594          break;
595
596       case GDCM_DICOMDIR_STUDY:
597          elemList = gdcmGlobal::GetDicomDirElements()->GetDicomDirStudyElements();
598          break;
599
600       case GDCM_DICOMDIR_PATIENT:
601          elemList = gdcmGlobal::GetDicomDirElements()->GetDicomDirPatientElements();
602          break;
603   
604       case GDCM_DICOMDIR_META:
605          elemList = gdcmGlobal::GetDicomDirElements()->GetDicomDirMetaElements();
606          break;
607
608       default:
609          return;
610    }
611
612    for( it = elemList.begin(); it != elemList.end(); ++it)
613    {
614       tmpGr     = it->group;
615       tmpEl     = it->elem;
616       dictEntry = GetPubDict()->GetDictEntryByNumber(tmpGr, tmpEl);
617       entry     = new gdcmValEntry( dictEntry ); // Be sure it's never a BinEntry !
618
619       entry->SetOffset(0); // just to avoid further missprinting
620
621       if( header ) // NULL when we Build Up (ex nihilo) a DICOMDIR
622                    //   or when we add the META elems
623       {
624          val = header->GetEntryByNumber(tmpGr, tmpEl);
625       }
626       else
627       {
628          val = GDCM_UNFOUND;
629       }
630
631       if( val == GDCM_UNFOUND) 
632       {
633          if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
634          {
635            // force to the *end* File Name
636            val = GetName( path );
637          }
638          else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
639          {
640             if( header->GetFileName().substr(0, path.length()) != path )
641             {
642                dbg.Verbose(0, "gdcmDicomDir::SetElement : the base path"
643                               " of file name is incorrect");
644                val = header->GetFileName();
645             }
646             else
647             {
648                val = &(header->GetFileName().c_str()[path.length()]);
649             }   
650          }
651          else
652          {
653             val = it->value;
654          }
655       }
656       else
657       {
658          if ( header->GetEntryLengthByNumber(tmpGr,tmpEl) == 0 )
659          {
660             val = it->value;
661          }
662       }
663
664       entry->SetValue( val );
665
666       if( dictEntry )
667       {
668          if( dictEntry->GetGroup() == 0xfffe )
669          {
670             entry->SetLength( entry->GetValue().length() ); // FIXME 
671          }
672          else if( dictEntry->GetVR() == "UL" || dictEntry->GetVR() == "SL" )
673          {
674             entry->SetLength(4);
675          }
676          else if( dictEntry->GetVR() == "US" || dictEntry->GetVR() == "SS" )
677          {
678             entry->SetLength(2); 
679          }
680          else if( dictEntry->GetVR() == "SQ" )
681          {
682             entry->SetLength( 0xffffffff );
683          }
684          else
685          {
686             entry->SetLength( entry->GetValue().length() );
687          }
688       }
689       std::cout << " was TagHT[entry->GetKey()] = entry " << std::endl;
690       if ( type == GDCM_DICOMDIR_META ) {
691          std::cout << " special Treatment for GDCM_DICOMDIR_META" << std::endl;
692          
693       }
694       //TagHT[entry->GetKey()] = entry;          // FIXME : use a SEQUENCE !
695    }
696 }
697
698 /**
699  * \brief   CallStartMethod
700  */
701 void gdcmDicomDir::CallStartMethod()
702 {
703    progress = 0.0f;
704    abort    = false;
705    if( startMethod )
706    {
707       startMethod( startArg );
708    }
709 }
710
711 /**
712  * \ingroup gdcmDicomDir
713  * \brief   CallProgressMethod
714  */
715 void gdcmDicomDir::CallProgressMethod()
716 {
717    if( progressMethod )
718    {
719       progressMethod( progressArg );
720    }
721 }
722
723 /**
724  * \ingroup gdcmDicomDir
725  * \brief   CallEndMethod
726  */
727 void gdcmDicomDir::CallEndMethod()
728 {
729    progress = 1.0f;
730    if( endMethod )
731    {
732       endMethod( endArg );
733    }
734 }
735
736 //-----------------------------------------------------------------------------
737 // Private
738 /**
739  * \ingroup gdcmDicomDir
740  * \brief create a 'gdcmDicomDir' from a DICOMDIR gdcmHeader 
741  */
742 void gdcmDicomDir::CreateDicomDir()
743 {
744    // The list is parsed. 
745    //  When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
746    //  1 - we save the beginning iterator
747    //  2 - we continue to parse
748    //  3 - we find an other tag
749    //       + we create the object for the precedent tag
750    //       + loop to 1 -
751
752    // Directory record sequence
753    gdcmDocEntry *e = GetDocEntryByNumber(0x0004, 0x1220);
754    if ( !e )
755    {
756       dbg.Verbose(0, "gdcmDicomDir::gdcmDicomDir : NO Directory record"
757                      " sequence (0x0004,0x1220)");
758       /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ? 
759       return;         
760    }
761    
762    gdcmSeqEntry* s = dynamic_cast<gdcmSeqEntry*>(e);
763    if ( !s )
764    {
765       dbg.Verbose(0, "gdcmDicomDir::CreateDicomDir: no SeqEntry present");
766       // useless : (0x0004,0x1220) IS a Sequence !
767       return;
768    }
769
770    gdcmDicomDirType type = gdcmDicomDir::GDCM_DICOMDIR_META;
771    metaElems = NewMeta();
772
773    ListSQItem listItems = s->GetSQItems();
774    
775    gdcmDocEntry * d;
776    std::string v;
777    for( ListSQItem::iterator i = listItems.begin(); 
778                              i !=listItems.end(); ++i ) 
779    {
780       d = (*i)->GetDocEntryByNumber(0x0004, 0x1430); // Directory Record Type
781       if ( gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(d) )
782       {
783          v = ValEntry->GetValue();
784       }
785       else
786       {
787          dbg.Verbose(0, "gdcmDicomDir::CreateDicomDir: not a ValEntry.");
788          continue;
789       }
790
791       if( v == "PATIENT " )
792       {
793          AddDicomDirPatientToEnd( *i );
794          //AddObjectToEnd(type,*i);
795          type = gdcmDicomDir::GDCM_DICOMDIR_PATIENT;
796       }
797       else if( v == "STUDY " )
798       {
799          AddDicomDirStudyToEnd( *i );
800         // AddObjectToEnd(type,*i);
801          type = gdcmDicomDir::GDCM_DICOMDIR_STUDY;
802       }
803       else if( v == "SERIES" )
804       {
805          AddDicomDirSerieToEnd( *i );
806          //  AddObjectToEnd(type,*i);
807          type = gdcmDicomDir::GDCM_DICOMDIR_SERIE;
808       }
809       else if( v == "IMAGE " ) 
810       {
811          AddDicomDirImageToEnd( *i );
812          //   AddObjectToEnd(type,*i);
813          type = gdcmDicomDir::GDCM_DICOMDIR_IMAGE;
814       }
815       else
816       {
817          // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
818          // neither an 'IMAGE' SQItem. Skip to next item.
819          continue;
820       }
821    }
822 }
823
824 /**
825  * \ingroup gdcmDicomDir
826  * \brief   AddObjectToEnd
827  * @param   type
828  * @param   begin iterator on the first DocEntry within the chained List
829  * @param   end iterator on the last DocEntry within the chained List
830  */
831  
832 // now  useless ?
833
834 /*void gdcmDicomDir::AddObjectToEnd(gdcmDicomDirType type,gdcmSQItem *s)
835 {
836    if(s==NULL) // ??
837       return;
838
839    switch(type)
840    {
841       case gdcmDicomDir::GDCM_DICOMDIR_META:
842          AddDicomDirMeta();
843          break;      
844       case gdcmDicomDir::GDCM_DICOMDIR_PATIENT:
845          AddDicomDirPatientToEnd(s);
846          break;
847       case gdcmDicomDir::GDCM_DICOMDIR_STUDY:
848          AddDicomDirStudyToEnd(s);
849          break;
850       case gdcmDicomDir::GDCM_DICOMDIR_SERIE:
851          AddDicomDirSerieToEnd(s);
852          break;
853       case gdcmDicomDir::GDCM_DICOMDIR_IMAGE:
854          AddDicomDirImageToEnd(s);
855          break;
856       case gdcmDicomDir::GDCM_DICOMDIR_NONE:
857          AddDicomDirImageToEnd(s);        //FIXME
858          break;
859    }
860 }
861
862 */
863
864 /**
865  * \ingroup gdcmDicomDir
866  * \brief Well ... there is only one occurence  
867  */
868 void gdcmDicomDir::AddDicomDirMeta()
869 {
870    if( metaElems )
871    {
872       delete metaElems;
873    }
874    metaElems = new gdcmDicomDirMeta( &TagHT );
875 }
876
877 /**
878  * \ingroup gdcmDicomDir
879  * \brief  AddDicomDirPatientToEnd 
880  * @param   s SQ Item to enqueue to the DicomPatient chained List
881  */
882 void gdcmDicomDir::AddDicomDirPatientToEnd(gdcmSQItem *s)
883 {
884    patients.push_back(new gdcmDicomDirPatient(s, &TagHT));
885 }
886
887 /**
888  * \ingroup gdcmDicomDir
889  * \brief  AddDicomDirStudyToEnd 
890  * @param   s SQ Item to enqueue to the DicomDirStudy chained List
891  */
892  void gdcmDicomDir::AddDicomDirStudyToEnd(gdcmSQItem *s)
893 {
894    if( patients.size() > 0 )
895    {
896       ListDicomDirPatient::iterator itp = patients.end();
897       itp--;
898       (*itp)->AddDicomDirStudy(new gdcmDicomDirStudy(s, &TagHT));
899    }
900 }
901
902 /**
903  * \ingroup gdcmDicomDir
904  * \brief  AddDicomDirSerieToEnd 
905  * @param   s SQ Item to enqueue to the DicomDirSerie chained List
906  */
907 void gdcmDicomDir::AddDicomDirSerieToEnd(gdcmSQItem *s)
908 {
909    if( patients.size() > 0 )
910    {
911       ListDicomDirPatient::iterator itp = patients.end();
912       itp--;
913
914       if( (*itp)->GetDicomDirStudies().size() > 0 )
915       {
916          ListDicomDirStudy::iterator itst=(*itp)->GetDicomDirStudies().end();
917          itst--;
918          (*itst)->AddDicomDirSerie(new gdcmDicomDirSerie(s, &TagHT));
919       }
920    }
921 }
922
923 /**
924  * \ingroup gdcmDicomDir
925  * \brief   AddDicomDirImageToEnd
926  * @param   s SQ Item to enqueue to the DicomDirImage chained List
927  */
928  void gdcmDicomDir::AddDicomDirImageToEnd(gdcmSQItem *s)
929 {
930    if( patients.size() > 0 )
931    {
932       ListDicomDirPatient::iterator itp = patients.end();
933       itp--;
934
935       if( (*itp)->GetDicomDirStudies().size() > 0 )
936       {
937          ListDicomDirStudy::iterator itst = (*itp)->GetDicomDirStudies().end();
938          itst--;
939
940          if( (*itst)->GetDicomDirSeries().size() > 0 )
941          {
942             ListDicomDirSerie::iterator its = (*itst)->GetDicomDirSeries().end();
943             its--;
944             (*its)->AddDicomDirImage(new gdcmDicomDirImage(s, &TagHT));
945          }
946       }
947    }
948 }
949
950 /**
951  * \ingroup gdcmDicomDir
952  * \brief  for each Header of the chained list, add/update the Patient/Study/Serie/Image info 
953  * @param   path path of the root directory
954  * @param   list chained list of Headers
955  */
956 void gdcmDicomDir::SetElements(std::string &path, VectDocument &list)
957 {
958    std::string patPrevName         = "", patPrevID  = "";
959    std::string studPrevInstanceUID = "", studPrevID = "";
960    std::string serPrevInstanceUID  = "", serPrevID  = "";
961
962    std::string patCurName,         patCurID;
963    std::string studCurInstanceUID, studCurID;
964    std::string serCurInstanceUID,  serCurID;
965
966    SetElement( path, GDCM_DICOMDIR_META,NULL);
967
968    for( VectDocument::iterator it = list.begin();
969                               it != list.end(); ++it )
970    {
971       // get the current file characteristics
972       patCurName         = (*it)->GetEntryByNumber(0x0010,0x0010); 
973       patCurID           = (*it)->GetEntryByNumber(0x0010,0x0011); 
974       studCurInstanceUID = (*it)->GetEntryByNumber(0x0020,0x000d);            
975       studCurID          = (*it)->GetEntryByNumber(0x0020,0x0010);            
976       serCurInstanceUID  = (*it)->GetEntryByNumber(0x0020,0x000e);            
977       serCurID           = (*it)->GetEntryByNumber(0x0020,0x0011);
978
979       if( patCurName != patPrevName || patCurID != patPrevID)
980       {
981          SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
982       }
983
984       // if new Study Deal with 'STUDY' Elements   
985       if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID )
986       {
987          SetElement(path, GDCM_DICOMDIR_STUDY, *it);
988       }
989
990       // if new Serie Deal with 'SERIE' Elements   
991       if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID )
992       {
993          SetElement(path, GDCM_DICOMDIR_SERIE, *it);
994       }
995       
996       // Always Deal with 'IMAGE' Elements  
997       SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
998
999       patPrevName         = patCurName;
1000       patPrevID           = patCurID;
1001       studPrevInstanceUID = studCurInstanceUID;
1002       studPrevID          = studCurID;
1003       serPrevInstanceUID  = serCurInstanceUID;
1004       serPrevID           = serCurID;
1005    }
1006 }
1007
1008 /**
1009  * \ingroup gdcmDicomDir
1010  * \brief   compares two dgcmHeaders
1011  */
1012 bool gdcmDicomDir::HeaderLessThan(gdcmDocument *header1, gdcmDocument *header2)
1013 {
1014    return *header1 < *header2;
1015 }
1016
1017 /**
1018  * \brief   Sets the accurate value for the (0x0004,0x1220) element of a DICOMDIR
1019  */
1020 void gdcmDicomDir::UpdateDirectoryRecordSequenceLength()
1021 {
1022
1023 /// \todo FIXME : to go on compiling
1024 ///
1025 /// to be re written !
1026 ///   int offset = 0;
1027 ///   ListTag::iterator it;
1028 ///   uint16_t gr, el;
1029 ///   std::string vr;
1030 ///   for(it=listEntries.begin();it!=listEntries.end();++it) {
1031 ///      gr = (*it)->GetGroup();
1032 ///      el = (*it)->GetElement();
1033 ///      vr = (*it)->GetVR();      
1034 ///      if (gr !=0xfffe) {
1035 ///         if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ) {    
1036 ///            offset +=  4; // explicit VR AND OB, OW, SQ : 4 more bytes
1037 ///         }         
1038 ///         offset += 2 + 2 + 4 + (*it)->GetLength(); 
1039 ///      } else {
1040 ///         offset +=  4; // delimiters don't have a value.     
1041 ///      }            
1042 ///   }   
1043 ///   //bool res=SetEntryLengthByNumber(offset, 0x0004, 0x1220); // Hope there is no dupps.
1044 ///    SetEntryLengthByNumber(offset, 0x0004, 0x1220); // Hope there is no dupps.
1045 ///   return;
1046 ///
1047 }
1048
1049 //-----------------------------------------------------------------------------