]> Creatis software - gdcm.git/blob - src/gdcmDicomDir.cxx
* Remove memory leaks
[gdcm.git] / src / gdcmDicomDir.cxx
1 /*=========================================================================
2   
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDicomDir.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/10/19 13:15:38 $
7   Version:   $Revision: 1.161 $
8   
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12   
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16   
17 =========================================================================*/
18
19 //-----------------------------------------------------------------------------
20 //  For full DICOMDIR description, see:
21 //  PS 3.3-2003, pages 731-750
22 //-----------------------------------------------------------------------------
23 #include "gdcmDicomDir.h"
24 #include "gdcmDicomDirObject.h"
25 #include "gdcmDicomDirStudy.h"
26 #include "gdcmDicomDirSerie.h"
27 #include "gdcmDicomDirVisit.h"
28 #include "gdcmDicomDirImage.h"
29 #include "gdcmDicomDirPatient.h"
30 #include "gdcmDicomDirMeta.h"
31 #include "gdcmDicomDirElement.h"
32 #include "gdcmDirList.h"
33 #include "gdcmUtil.h"
34 #include "gdcmDebug.h"
35 #include "gdcmGlobal.h"
36 #include "gdcmFile.h"
37 #include "gdcmSeqEntry.h"
38 #include "gdcmSQItem.h"
39 #include "gdcmDataEntry.h"
40
41 #include <fstream>
42 #include <string>
43 #include <algorithm>
44 #include <sys/types.h>
45
46 #ifdef _MSC_VER
47 #   define getcwd _getcwd
48 #endif
49
50 #if defined(_MSC_VER) || defined(__BORLANDC__)
51 #   include <direct.h>
52 #else
53 #   include <unistd.h>
54 #endif
55 // ----------------------------------------------------------------------------
56 //         Note for future developpers
57 // ----------------------------------------------------------------------------
58 //
59 //  Dicom PS 3.3 describes the relationship between Directory Records, as follow
60 //    (see also PS 4.3, 2004, page 50 for Entity-Relationship model)
61 //
62 //  Directory Record Type      Directory Record Types which may be included
63 //                                in the next lower-level directory Entity
64 //
65 // (Root directory Entity)     PATIENT, TOPIC, PRIVATE
66 //
67 // PATIENT                     STUDY, PRIVATE
68 //
69 // STUDY                       SERIES, VISIT, RESULTS, STUDY COMPONENT, PRIVATE
70 //
71 // SERIES                      IMAGE, OVERLAYS, MODALITY LUT, VOI LUT,
72 //                             CURVE, STORED PRINT, RT DOSE, RT STRUCTURE SET
73 //                             RT PLAN, RT TREAT RECORD, PRESENTATION, WAVEFORM,
74 //                             SR DOCUMENT, KEY OBJECT DOC, SPECTROSCOPY,
75 //                             RAW DATA, REGISTRATION, FIDUCIAL, PRIVATE,
76 //                             ENCAP DOC
77 // IMAGE
78 // OVERLAY
79 // MODALITY LUT
80 // VOI LUT
81 // CURVE
82 // STORED PRINT
83 // RT DOSE
84 // RT STRUCTURE SET
85 // RT PLAN
86 // RT TREAT RECORD
87 // PRESENTATION
88 // WAVEFORM
89 // SR DOCUMENT
90 // KEY OBJECT DOC
91 // SPECTROSCOPY
92 // RAW DATA
93 // REGISTRATION
94 // FIDUCIAL
95 // PRIVATE
96 // ENCAP DOC
97 // 
98 // ----------------------
99 // The current gdcm version only deals with :
100 //
101 // (Root directory Entity)     PATIENT
102 // PATIENT                     STUDY
103 // STUDY                       SERIES
104 // STUDY                       VISIT 
105 // SERIES                      IMAGE
106 // IMAGE                       /
107 //
108 // DicomDir::CreateDicomDir will have to be completed
109 // Treelike structure management will have to be upgraded
110 // ----------------------------------------------------------------------------
111     
112 namespace gdcm 
113 {
114 //-----------------------------------------------------------------------------
115 // Constructor / Destructor
116 /**
117  * \brief   Constructor : creates an empty DicomDir
118  */
119 DicomDir::DicomDir()
120          :Document( )
121 {
122    Initialize();  // sets all private fields to NULL
123    ParseDir = false;
124    NewMeta();
125 }
126
127 #ifndef GDCM_LEGACY_REMOVE
128 /**
129  * \brief Constructor Parses recursively the directory and creates the DicomDir
130  *        or uses an already built DICOMDIR, depending on 'parseDir' value.
131  * @param fileName  name 
132  *                      - of the root directory (parseDir = true)
133  *                      - of the DICOMDIR       (parseDir = false)
134  * @param parseDir boolean
135  *                      - true if user passed an entry point 
136  *                        and wants to explore recursively the directories
137  *                      - false if user passed an already built DICOMDIR file
138  *                        and wants to use it 
139  * @deprecated use : new DicomDir() + [ SetLoadMode(lm) + ] SetDirectoryName(name)
140  *              or : new DicomDir() + SetFileName(name)
141  */
142 DicomDir::DicomDir(std::string const &fileName, bool parseDir ):
143    Document( )
144 {
145    // At this step, Document constructor is already executed,
146    // whatever user passed (either a root directory or a DICOMDIR)
147    // and whatever the value of parseDir was.
148    // (nothing is cheked in Document constructor, to avoid overhead)
149
150    ParseDir = parseDir;
151    SetLoadMode (LD_ALL); // concerns only dicom files
152    SetFileName( fileName );
153    Load( );
154 }
155 #endif
156
157 /**
158  * \brief  Canonical destructor 
159  */
160 DicomDir::~DicomDir() 
161 {
162    SetStartMethod(NULL,NULL,NULL);
163    SetProgressMethod(NULL,NULL,NULL);
164    SetEndMethod(NULL,NULL,NULL);
165
166    ClearPatient();
167    if ( MetaElems )
168    {
169       delete MetaElems;
170    }
171 }
172
173 //-----------------------------------------------------------------------------
174 // Public
175
176 /**
177  * \brief   Loader. use SetFileName(fn) 
178  *                  or SetLoadMode(lm) + SetDirectoryName(dn)  before !  
179  * @return false if file cannot be open or no swap info was found,
180  *         or no tag was found.
181  */
182 bool DicomDir::Load( ) 
183 {
184    if (!ParseDir)
185    {
186       if ( ! this->Document::Load( ) )
187          return false;
188    }
189    return DoTheLoadingJob( );   
190 }
191
192 #ifndef GDCM_LEGACY_REMOVE
193 /**
194  * \brief   Loader. (DEPRECATED : kept not to break the API)
195  * @param   fileName file to be open for parsing
196  * @return false if file cannot be open or no swap info was found,
197  *         or no tag was found.
198  * @deprecated use SetFileName(n) + Load() instead
199  */
200 bool DicomDir::Load(std::string const &fileName ) 
201 {
202    // We should clean out anything that already exists.
203    Initialize();  // sets all private fields to NULL
204    return Load();
205 }
206
207 /// DEPRECATED : use SetDirectoryName(dname) instead
208 /**
209  * \brief   Loader. (DEPRECATED : kept not to break the API)
210  * @param   paseDir Parse Dir
211  * @deprecated use SetDirectoryName(dname) instead
212  */
213 void DicomDir::SetParseDir(bool parseDir)
214 {
215    ParseDir = parseDir;
216 }
217 #endif
218
219 /**
220  * \brief   Does the Loading Job (internal use only)
221  * @return false if file cannot be open or no swap info was found,
222  *         or no tag was found.
223  */
224 bool DicomDir::DoTheLoadingJob( ) 
225 {
226    Progress = 0.0f;
227    Abort = false;
228
229    if (!ParseDir)
230    {
231    // Only if user passed a DICOMDIR
232    // ------------------------------
233       Fp = 0;
234       if (!Document::Load() )
235       {
236          return false;
237       }
238
239       if ( GetFirstEntry() == 0 ) // when user passed a Directory to parse
240       {
241          gdcmWarningMacro( "Entry HT empty for file: "<< GetFileName());
242          return false;
243       }
244       // Directory record sequence
245       DocEntry *e = GetDocEntry(0x0004, 0x1220);
246       if ( !e )
247       {
248          gdcmWarningMacro( "NO 'Directory record sequence' (0x0004,0x1220)"
249                           << " in file " << GetFileName());
250          return false;
251       }
252       else
253          CreateDicomDir();
254    }
255    else
256    {
257    // Only if user passed a root directory
258    // ------------------------------------
259       if ( GetFileName() == "." )
260       {
261          // user passed '.' as Name
262          // we get current directory name
263          char dummy[1000];
264          getcwd(dummy, (size_t)1000);
265          SetFileName( dummy ); // will be converted into a string
266       }
267       NewMeta();
268       gdcmWarningMacro( "Parse directory and create the DicomDir : " 
269                          << GetFileName() );
270       ParseDirectory();
271    }
272    return true;
273 }
274
275 /**
276  * \brief  This predicate, based on hopefully reasonable heuristics,
277  *         decides whether or not the current document was properly parsed
278  *         and contains the mandatory information for being considered as
279  *         a well formed and usable DicomDir.
280  * @return true when Document is the one of a reasonable DicomDir,
281  *         false otherwise. 
282  */
283 bool DicomDir::IsReadable()
284 {
285    if ( Filetype == Unknown )
286    {
287       gdcmWarningMacro( "Wrong filetype");
288       return false;
289    }
290    if ( !MetaElems )
291    {
292       gdcmWarningMacro( "Meta Elements missing in DicomDir");
293       return false;
294    }
295    if ( Patients.size() <= 0 )
296    {
297       gdcmWarningMacro( "NO Patient in DicomDir");
298       return false;
299    }
300
301    return true;
302 }
303
304 /**
305  * \brief   adds *the* Meta to a partially created DICOMDIR
306  */  
307 DicomDirMeta *DicomDir::NewMeta()
308 {
309    if ( MetaElems )
310       delete MetaElems;
311
312    DocEntry *entry = GetFirstEntry();
313    if ( entry )
314    { 
315       MetaElems = new DicomDirMeta(true); // true = empty
316
317       entry = GetFirstEntry();
318       while( entry )
319       {
320          if ( dynamic_cast<SeqEntry *>(entry) )
321             break;
322
323          RemoveEntryNoDestroy(entry);
324          MetaElems->AddEntry(entry);
325
326          entry = GetFirstEntry();
327       }
328    }
329    else  // after root directory parsing
330    {
331       MetaElems = new DicomDirMeta(false); // false = not empty
332    }
333    MetaElems->SetSQItemNumber(0); // To avoid further missprinting
334    return MetaElems;  
335 }
336
337 /**
338  * \brief   adds a new Patient (with the basic elements) to a partially created
339  *          DICOMDIR
340  */
341 DicomDirPatient *DicomDir::NewPatient()
342 {
343    DicomDirPatient *p = new DicomDirPatient();
344    AddPatientToEnd( p );
345    return p;
346 }
347
348 /**
349  * \brief   Remove all Patients
350  */
351 void DicomDir::ClearPatient()
352 {
353    for(ListDicomDirPatient::iterator cc = Patients.begin();
354                                      cc!= Patients.end();
355                                    ++cc)
356    {
357       delete *cc;
358    }
359    Patients.clear();
360 }
361
362 /**
363  * \brief   Get the first entry while visiting the DicomDirPatients
364  * \return  The first DicomDirPatient if found, otherwhise NULL
365  */ 
366 DicomDirPatient *DicomDir::GetFirstPatient()
367 {
368    ItPatient = Patients.begin();
369    if ( ItPatient != Patients.end() )
370       return *ItPatient;
371    return NULL;
372 }
373
374 /**
375  * \brief   Get the next entry while visiting the DicomDirPatients
376  * \note : meaningfull only if GetFirstEntry already called
377  * \return  The next DicomDirPatient if found, otherwhise NULL
378  */
379 DicomDirPatient *DicomDir::GetNextPatient()
380 {
381    gdcmAssertMacro (ItPatient != Patients.end());
382
383    ++ItPatient;
384    if ( ItPatient != Patients.end() )
385       return *ItPatient;
386    return NULL;
387 }
388
389 /**
390  * \brief  fills the whole structure, starting from a root Directory
391  */
392 void DicomDir::ParseDirectory()
393 {
394    CreateDicomDirChainedList( GetFileName() );
395    CreateDicomDir();
396 }
397
398 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg )
399 {
400    SetStartMethod(method,arg,NULL);
401 }
402
403 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg )
404 {
405    SetProgressMethod(method,arg,NULL);
406 }
407
408 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg )
409 {
410    SetEndMethod(method,arg,NULL);
411 }
412
413 /**
414  * \brief   Set the start method to call when the parsing of the
415  *          directory starts.
416  * @param   method Method to call
417  * @param   arg    Argument to pass to the method
418  * @param   argDelete    Argument 
419  * \warning In python : the arg parameter isn't considered
420  */
421 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg, 
422                                DicomDir::Method *argDelete )
423 {
424    if ( StartArg && StartMethodArgDelete )
425    {
426       StartMethodArgDelete( StartArg );
427    }
428
429    StartMethod          = method;
430    StartArg             = arg;
431    StartMethodArgDelete = argDelete;
432 }
433
434
435 /**
436  * \brief   Set the progress method to call when the parsing of the
437  *          directory progress
438  * @param   method Method to call
439  * @param   arg    Argument to pass to the method
440  * @param   argDelete    Argument  
441  * \warning In python : the arg parameter isn't considered
442  */
443 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg, 
444                                   DicomDir::Method *argDelete )
445 {
446    if ( ProgressArg && ProgressMethodArgDelete )
447    {
448       ProgressMethodArgDelete( ProgressArg );
449    }
450
451    ProgressMethod          = method;
452    ProgressArg             = arg;
453    ProgressMethodArgDelete = argDelete;
454 }
455
456 /**
457  * \brief   Set the end method to call when the parsing of the directory ends
458  * @param   method Method to call
459  * @param   arg    Argument to pass to the method
460  * @param   argDelete    Argument 
461  * \warning In python : the arg parameter isn't considered
462  */
463 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg, 
464                              DicomDir::Method *argDelete )
465 {
466    if ( EndArg && EndMethodArgDelete )
467    {
468       EndMethodArgDelete( EndArg );
469    }
470
471    EndMethod          = method;
472    EndArg             = arg;
473    EndMethodArgDelete = argDelete;
474 }
475
476 /**
477  * \brief   Set the method to delete the argument
478  *          The argument is destroyed when the method is changed or when the
479  *          class is destroyed
480  * @param   method Method to call to delete the argument
481  */
482 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method ) 
483 {
484    StartMethodArgDelete = method;
485 }
486
487 /**
488  * \brief   Set the method to delete the argument
489  *          The argument is destroyed when the method is changed or when the 
490  *          class is destroyed          
491  * @param   method Method to call to delete the argument
492  */
493 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method *method )
494 {
495    ProgressMethodArgDelete = method;
496 }
497
498 /**
499  * \brief   Set the method to delete the argument
500  *          The argument is destroyed when the method is changed or when
501  *          the class is destroyed
502  * @param   method Method to call to delete the argument
503  */
504 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
505 {
506    EndMethodArgDelete = method;
507 }
508
509 /**
510  * \brief    writes on disc a DICOMDIR
511  * \ warning does NOT add the missing elements in the header :
512  *           it's up to the user doing it !
513  * @param  fileName file to be written to 
514  * @return false only when fail to open
515  */
516  
517 bool DicomDir::Write(std::string const &fileName) 
518 {  
519    int i;
520    uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
521    uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
522
523    std::ofstream *fp = new std::ofstream(fileName.c_str(),  
524                                          std::ios::out | std::ios::binary);
525    if ( !fp ) 
526    {
527       gdcmWarningMacro("Failed to open(write) File: " << fileName.c_str());
528       return false;
529    }
530
531    char filePreamble[128];
532    memset(filePreamble, 0, 128);
533    fp->write(filePreamble, 128);
534    binary_write( *fp, "DICM");
535  
536    DicomDirMeta *ptrMeta = GetMeta();
537    ptrMeta->WriteContent(fp, ExplicitVR);
538    
539    // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
540    for(i=0;i<4;++i)
541    {
542       binary_write(*fp, sq[i]);
543    }
544         
545    for(ListDicomDirPatient::iterator cc  = Patients.begin();
546                                      cc != Patients.end();
547                                    ++cc )
548    {
549       (*cc)->WriteContent( fp, ExplicitVR );
550    }
551    
552    // force writing Sequence Delimitation Item
553    for(i=0;i<4;++i)
554    {
555       binary_write(*fp, sqt[i]);  // fffe e0dd ffff ffff 
556    }
557
558    fp->close();
559    delete fp;
560
561    return true;
562 }
563
564 /**
565  * \brief    Anonymize a DICOMDIR
566  * @return true 
567  */
568  
569 bool DicomDir::Anonymize() 
570 {
571    DataEntry *v;
572    // Something clever to be found to forge the Patient names
573    std::ostringstream s;
574    int i = 1;
575    for(ListDicomDirPatient::iterator cc = Patients.begin();
576                                      cc!= Patients.end();
577                                    ++cc)
578    {
579       s << i;
580       v = (*cc)->GetDataEntry(0x0010, 0x0010) ; // Patient's Name
581       if (v)
582       {
583          v->SetString(s.str());
584       }
585
586       v = (*cc)->GetDataEntry(0x0010, 0x0020) ; // Patient ID
587       if (v)
588       {
589          v->SetString(" ");
590       }
591
592       v = (*cc)->GetDataEntry(0x0010, 0x0030) ; // Patient's BirthDate
593       if (v)
594       {
595          v->SetString(" ");
596       }
597       s << "";
598       i++;
599    }
600    return true;
601 }
602
603 //-----------------------------------------------------------------------------
604 // Protected
605 /**
606  * \brief create a Document-like chained list from a root Directory 
607  * @param path entry point of the tree-like structure
608  */
609 void DicomDir::CreateDicomDirChainedList(std::string const &path)
610 {
611    CallStartMethod();
612    DirList dirList(path,1); // gets recursively the file list
613    unsigned int count = 0;
614    VectDocument list;
615    File *f;
616
617    DirListType fileList = dirList.GetFilenames();
618
619    for( DirListType::iterator it  = fileList.begin();
620                               it != fileList.end();
621                               ++it )
622    {
623       Progress = (float)(count+1)/(float)fileList.size();
624       CallProgressMethod();
625       if ( Abort )
626       {
627          break;
628       }
629
630       f = new File( );
631       f->SetLoadMode(LoadMode); // we allow user not to load Sequences, or Shadow
632                               //             groups, or ......
633       f->SetFileName( it->c_str() );
634    /*int res = */f->Load( );
635
636 //     if ( !f )
637 //     {
638 //         gdcmWarningMacro( "Failure in new gdcm::File " << it->c_str() );
639 //         continue;
640 //      }
641       
642       if ( f->IsReadable() )
643       {
644          // Add the file to the chained list:
645          list.push_back(f);
646          gdcmWarningMacro( "Readable " << it->c_str() );
647        }
648        else
649        {
650           delete f;
651        }
652        count++;
653    }
654    // sorts Patient/Study/Serie/
655    std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
656    
657    std::string tmp = dirList.GetDirName();      
658    //for each File of the chained list, add/update the Patient/Study/Serie/Image info
659    SetElements(tmp, list);
660    CallEndMethod();
661
662    for(VectDocument::iterator itDoc=list.begin();
663        itDoc!=list.end();
664        ++itDoc)
665    {
666       delete dynamic_cast<File *>(*itDoc);
667    }
668 }
669
670 /**
671  * \brief   CallStartMethod
672  */
673 void DicomDir::CallStartMethod()
674 {
675    Progress = 0.0f;
676    Abort    = false;
677    if ( StartMethod )
678    {
679       StartMethod( StartArg );
680    }
681 }
682
683 /**
684  * \brief   CallProgressMethod
685  */
686 void DicomDir::CallProgressMethod()
687 {
688    if ( ProgressMethod )
689    {
690       ProgressMethod( ProgressArg );
691    }
692 }
693
694 /**
695  * \brief   CallEndMethod
696  */
697 void DicomDir::CallEndMethod()
698 {
699    Progress = 1.0f;
700    if ( EndMethod )
701    {
702       EndMethod( EndArg );
703    }
704 }
705
706 //-----------------------------------------------------------------------------
707 // Private
708 /**
709  * \brief Sets all fields to NULL
710  */
711 void DicomDir::Initialize()
712 {
713    StartMethod             = NULL;
714    ProgressMethod          = NULL;
715    EndMethod               = NULL;
716    StartMethodArgDelete    = NULL;
717    ProgressMethodArgDelete = NULL;
718    EndMethodArgDelete      = NULL;
719    StartArg                = NULL;
720    ProgressArg             = NULL;
721    EndArg                  = NULL;
722
723    Progress = 0.0;
724    Abort = false;
725
726    MetaElems = NULL;   
727 }
728
729 /**
730  * \brief create a 'gdcm::DicomDir' from a DICOMDIR Header 
731  */
732 void DicomDir::CreateDicomDir()
733 {
734    // The SeqEntries of "Directory Record Sequence" are parsed. 
735    //  When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
736    //  1 - we save the beginning iterator
737    //  2 - we continue to parse
738    //  3 - we find an other tag
739    //       + we create the object for the precedent tag
740    //       + loop to 1 -
741
742    // Directory record sequence
743    DocEntry *e = GetDocEntry(0x0004, 0x1220);
744    if ( !e )
745    {
746       gdcmWarningMacro( "No Directory Record Sequence (0004,1220) found");
747       return;         
748    }
749    
750    SeqEntry *s = dynamic_cast<SeqEntry *>(e);
751    if ( !s )
752    {
753       gdcmWarningMacro( "Element (0004,1220) is not a Sequence ?!?");
754       return;
755    }
756
757    NewMeta();
758    
759    DocEntry *d;
760    std::string v;
761    SQItem *si;
762
763    SQItem *tmpSI=s->GetFirstSQItem();
764    while(tmpSI)
765    {
766       d = tmpSI->GetDocEntry(0x0004, 0x1430); // Directory Record Type
767       if ( DataEntry *dataEntry = dynamic_cast<DataEntry *>(d) )
768       {
769          v = dataEntry->GetString();
770       }
771       else
772       {
773          gdcmWarningMacro( "(0004,1430) not a DataEntry ?!?");
774          continue;
775       }
776
777       // A decent DICOMDIR has much more images than series,
778       // more series than studies, and so on.
779       // This is the right order to preform the tests
780
781       if ( v == "IMAGE " ) 
782       {
783          si = new DicomDirImage(true);
784          if ( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
785          {
786             delete si;
787             si = NULL;
788             gdcmErrorMacro( "Add AddImageToEnd failed");
789          }
790       }
791       else if ( v == "SERIES" )
792       {
793          si = new DicomDirSerie(true);
794          if ( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
795          {
796             delete si;
797             si = NULL;
798             gdcmErrorMacro( "Add AddSerieToEnd failed");
799          }
800       }
801       else if ( v == "VISIT " )
802       {
803          si = new DicomDirVisit(true);
804          if ( !AddVisitToEnd( static_cast<DicomDirVisit *>(si)) )
805          {
806             delete si;
807             si = NULL;
808             gdcmErrorMacro( "Add AddVisitToEnd failed");
809          }
810       }
811       else if ( v == "STUDY " )
812       {
813          si = new DicomDirStudy(true);
814          if ( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
815          {
816             delete si;
817             si = NULL;
818             gdcmErrorMacro( "Add AddStudyToEnd failed");
819          }
820       }
821       else if ( v == "PATIENT " )
822       {
823          si = new DicomDirPatient(true);
824          if ( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
825          {
826             delete si;
827             si = NULL;
828             gdcmErrorMacro( "Add PatientToEnd failed");
829          }
830       }
831       else
832       {
833          // It was neither a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
834          // nor an 'IMAGE' SQItem. Skip to next item.
835          gdcmWarningMacro( " -------------------------------------------"
836          << "a non PATIENT/STUDY/SERIE/IMAGE SQItem was found : "
837          << v);
838
839         // FIXME : deal with other item types !
840         tmpSI=s->GetNextSQItem(); // To avoid infinite loop
841         continue;
842       }
843       if ( si )
844          si->MoveObject(tmpSI);  // New code : Copies the List
845
846       tmpSI=s->GetNextSQItem();
847    }
848    ClearEntry();
849 }
850
851 /**
852  * \brief  AddPatientToEnd 
853  * @param   dd SQ Item to enqueue to the DicomPatient chained List
854  */
855 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
856 {
857    Patients.push_back(dd);
858    return true;
859 }
860
861 /**
862  * \brief  AddStudyToEnd 
863  * @param   dd SQ Item to enqueue to the DicomDirStudy chained List
864  */
865 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
866 {
867    if ( Patients.size() > 0 )
868    {
869       ListDicomDirPatient::iterator itp = Patients.end();
870       itp--;
871       (*itp)->AddStudy(dd);
872       return true;
873    }
874    return false;
875 }
876
877 /**
878  * \brief  AddSerieToEnd 
879  * @param   dd SQ Item to enqueue to the DicomDirSerie chained List
880  */
881 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
882 {
883    if ( Patients.size() > 0 )
884    {
885       ListDicomDirPatient::iterator itp = Patients.end();
886       itp--;
887
888       DicomDirStudy *study = (*itp)->GetLastStudy();
889       if ( study )
890       {
891          study->AddSerie(dd);
892          return true;
893       }
894    }
895    return false;
896 }
897
898 /**
899  * \brief  AddVisitToEnd 
900  * @param   dd SQ Item to enqueue to the DicomDirVisit chained List
901  */
902 bool DicomDir::AddVisitToEnd(DicomDirVisit *dd)
903 {
904    if ( Patients.size() > 0 )
905    {
906       ListDicomDirPatient::iterator itp = Patients.end();
907       itp--;
908
909       DicomDirStudy *study = (*itp)->GetLastStudy();
910       if ( study )
911       {
912          study->AddVisit(dd);
913          return true;
914       }
915    }
916    return false;
917 }
918 /**
919  * \brief   AddImageToEnd
920  * @param   dd SQ Item to enqueue to the DicomDirImage chained List
921  */
922 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
923 {
924    if ( Patients.size() > 0 )
925    {
926       ListDicomDirPatient::iterator itp = Patients.end();
927       itp--;
928
929       DicomDirStudy *study = (*itp)->GetLastStudy();
930       if ( study )
931       {
932          DicomDirSerie *serie = study->GetLastSerie();
933          if ( serie )
934          {
935             serie->AddImage(dd);
936             return true;
937          }
938       }
939    }
940    return false;
941 }
942
943 /**
944  * \brief  for each Header of the chained list, 
945  *         add/update the Patient/Study/Serie/Image info 
946  * @param   path path of the root directory
947  * @param   list chained list of Headers
948  */
949 void DicomDir::SetElements(std::string const &path, VectDocument const &list)
950 {
951    ClearEntry();
952    ClearPatient();
953
954    std::string patPrevName         = "", patPrevID  = "";
955    std::string studPrevInstanceUID = "", studPrevID = "";
956    std::string serPrevInstanceUID  = "", serPrevID  = "";
957
958    std::string patCurName,         patCurID;
959    std::string studCurInstanceUID, studCurID;
960    std::string serCurInstanceUID,  serCurID;
961
962    bool first = true;
963    for( VectDocument::const_iterator it = list.begin();
964                                      it != list.end(); 
965                                    ++it )
966    {
967       // get the current file characteristics
968       patCurName         = (*it)->GetEntryString(0x0010,0x0010);
969       patCurID           = (*it)->GetEntryString(0x0010,0x0011);
970       studCurInstanceUID = (*it)->GetEntryString(0x0020,0x000d);
971       studCurID          = (*it)->GetEntryString(0x0020,0x0010);
972       serCurInstanceUID  = (*it)->GetEntryString(0x0020,0x000e);
973       serCurID           = (*it)->GetEntryString(0x0020,0x0011);
974
975       if ( patCurName != patPrevName || patCurID != patPrevID || first )
976       {
977          SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
978          first = true;
979       }
980
981       // if new Study, deal with 'STUDY' Elements   
982       if ( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID 
983          || first )
984       {
985          SetElement(path, GDCM_DICOMDIR_STUDY, *it);
986          first = true;
987       }
988
989       // if new Serie, deal with 'SERIE' Elements   
990       if ( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
991          || first )
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       first = false;
1006    }
1007 }
1008
1009 /**
1010  * \brief   adds to the HTable 
1011  *          the Entries (Dicom Elements) corresponding to the given type
1012  * @param   path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
1013  * @param   type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
1014  *          GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
1015  * @param   header Header of the current file
1016  */
1017 void DicomDir::SetElement(std::string const &path, DicomDirType type,
1018                           Document *header)
1019 {
1020    ListDicomDirElem elemList;
1021    ListDicomDirElem::const_iterator it;
1022    uint16_t tmpGr, tmpEl;
1023    DictEntry *dictEntry;
1024    DataEntry *entry;
1025    std::string val;
1026    SQItem *si;
1027
1028    switch( type )
1029    {
1030       case GDCM_DICOMDIR_IMAGE:
1031          elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
1032          si = new DicomDirImage(true);
1033          if ( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
1034          {
1035             delete si;
1036             gdcmErrorMacro( "Add ImageToEnd failed");
1037          }
1038          break;
1039       case GDCM_DICOMDIR_SERIE:
1040          elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
1041          si = new DicomDirSerie(true);
1042          if ( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
1043          {
1044             delete si;
1045             gdcmErrorMacro( "Add SerieToEnd failed");
1046          }
1047          break;
1048       case GDCM_DICOMDIR_STUDY:
1049          elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
1050          si = new DicomDirStudy(true);
1051          if ( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
1052          {
1053             delete si;
1054             gdcmErrorMacro( "Add StudyToEnd failed");
1055          }
1056          break;
1057       case GDCM_DICOMDIR_PATIENT:
1058          elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
1059          si = new DicomDirPatient(true);
1060          if ( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
1061          {
1062             delete si;
1063             gdcmErrorMacro( "Add PatientToEnd failed");
1064          }
1065          break;
1066       case GDCM_DICOMDIR_META:
1067          if ( MetaElems )
1068          {
1069             delete MetaElems;
1070             gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
1071          }
1072          elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
1073          MetaElems = new DicomDirMeta(true);
1074          si = MetaElems;
1075          break;
1076       default:
1077          return;
1078    }
1079    // removed all the seems-to-be-useless stuff about Referenced Image Sequence
1080    // to avoid further troubles
1081    // imageElem 0008 1140 "" // Referenced Image Sequence
1082    // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
1083    // imageElem 0008 1150 "" // Referenced SOP Class UID    : to be set/forged later
1084    // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
1085    // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
1086  
1087    // FIXME : troubles found when it's a SeqEntry
1088
1089    // for all the relevant elements found in their own spot of the DicomDir.dic
1090    for( it = elemList.begin(); it != elemList.end(); ++it)
1091    {
1092       tmpGr     = it->Group;
1093       tmpEl     = it->Elem;
1094       dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
1095
1096       entry     = new DataEntry( dictEntry ); // Be sure it's never a DataEntry !
1097
1098       entry->SetOffset(0); // just to avoid further missprinting
1099
1100       if ( header )
1101       {
1102          // NULL when we Build Up (ex nihilo) a DICOMDIR
1103          //   or when we add the META elems
1104          val = header->GetEntryString(tmpGr, tmpEl);
1105       }
1106       else
1107       {
1108          val = GDCM_UNFOUND;
1109       }
1110
1111       if ( val == GDCM_UNFOUND) 
1112       {
1113          if ( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
1114          {
1115            // force to the *end* File Name
1116            val = Util::GetName( path );
1117          }
1118          else if ( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
1119          {
1120             if ( header->GetFileName().substr(0, path.length()) != path )
1121             {
1122                gdcmWarningMacro( "The base path of file name is incorrect");
1123                val = header->GetFileName();
1124             }
1125             else
1126             {
1127                val = &(header->GetFileName().c_str()[path.length()]);
1128             }
1129          }
1130          else
1131          {
1132             val = it->Value;
1133          }
1134       }
1135       else
1136       {
1137          if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
1138             val = it->Value;
1139       }
1140
1141       entry->SetString( val ); // troubles expected when vr=SQ ...
1142
1143       if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
1144       {
1145          gdcmWarningMacro("GDCM_DICOMDIR_META ?!? should never print that");
1146       }
1147       si->AddEntry(entry);
1148    }
1149 }
1150
1151 /**
1152  * \brief   Move the content of the source SQItem to the destination SQItem
1153  *          Only DocEntry's are moved
1154  * @param dst destination SQItem
1155  * @param src source SQItem
1156  */
1157 void DicomDir::MoveSQItem(DocEntrySet *dst,DocEntrySet *src)
1158
1159    DocEntry *entry;
1160
1161    entry = src->GetFirstEntry();
1162    while(entry)
1163    {
1164       src->RemoveEntryNoDestroy(entry);
1165       dst->AddEntry(entry);
1166       // we destroyed -> the current iterator is not longer valid
1167       entry = src->GetFirstEntry();
1168    }
1169 }
1170
1171 /**
1172  * \brief   compares two files
1173  */
1174 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
1175 {
1176    return *header1 < *header2;
1177 }
1178
1179 //-----------------------------------------------------------------------------
1180 // Print
1181 /**
1182  * \brief  Canonical Printer 
1183  * @param   os ostream we want to print in
1184  * @param indent Indentation string to be prepended during printing
1185  */
1186 void DicomDir::Print(std::ostream &os, std::string const & )
1187 {
1188    if ( MetaElems )
1189    {
1190       MetaElems->SetPrintLevel(PrintLevel);
1191       MetaElems->Print(os);   
1192    }   
1193    for(ListDicomDirPatient::iterator cc  = Patients.begin();
1194                                      cc != Patients.end();
1195                                    ++cc)
1196    {
1197      (*cc)->SetPrintLevel(PrintLevel);
1198      (*cc)->Print(os);
1199    }
1200 }
1201
1202 //-----------------------------------------------------------------------------
1203 } // end namespace gdcm