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