]> Creatis software - gdcm.git/blob - src/gdcmDicomDir.cxx
* Change the DocEntry inheritance to RefCounter
[gdcm.git] / src / gdcmDicomDir.cxx
1 /*=========================================================================
2   
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDicomDir.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/10/24 16:00:47 $
7   Version:   $Revision: 1.165 $
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    SetFileName(fileName);
203    return Load();
204 }
205
206 /// DEPRECATED : use SetDirectoryName(dname) instead
207 /* *
208  * \brief   Loader. (DEPRECATED : kept not to break the API)
209  * @param   paseDir Parse Dir
210  * @deprecated use SetDirectoryName(dname) instead
211  */
212 void DicomDir::SetParseDir(bool parseDir)
213 {
214    ParseDir = parseDir;
215 }
216 #endif
217
218 /**
219  * \brief   Does the Loading Job (internal use only)
220  * @return false if file cannot be open or no swap info was found,
221  *         or no tag was found.
222  */
223 bool DicomDir::DoTheLoadingJob( ) 
224 {
225    Progress = 0.0f;
226    Abort = false;
227
228    if (!ParseDir)
229    {
230    // Only if user passed a DICOMDIR
231    // ------------------------------
232       Fp = 0;
233       if (!Document::Load() )
234       {
235          return false;
236       }
237
238       if ( GetFirstEntry() == 0 ) // when user passed a Directory to parse
239       {
240          gdcmWarningMacro( "Entry HT empty for file: "<< GetFileName());
241          return false;
242       }
243       // Directory record sequence
244       DocEntry *e = GetDocEntry(0x0004, 0x1220);
245       if ( !e )
246       {
247          gdcmWarningMacro( "NO 'Directory record sequence' (0x0004,0x1220)"
248                           << " in file " << GetFileName());
249          return false;
250       }
251       else
252          CreateDicomDir();
253    }
254    else
255    {
256    // Only if user passed a root directory
257    // ------------------------------------
258       if ( GetFileName() == "." )
259       {
260          // user passed '.' as Name
261          // we get current directory name
262          char dummy[1000];
263          getcwd(dummy, (size_t)1000);
264          SetFileName( dummy ); // will be converted into a string
265       }
266       NewMeta();
267       gdcmWarningMacro( "Parse directory and create the DicomDir : " 
268                          << GetFileName() );
269       ParseDirectory();
270    }
271    return true;
272 }
273
274 /**
275  * \brief  This predicate, based on hopefully reasonable heuristics,
276  *         decides whether or not the current document was properly parsed
277  *         and contains the mandatory information for being considered as
278  *         a well formed and usable DicomDir.
279  * @return true when Document is the one of a reasonable DicomDir,
280  *         false otherwise. 
281  */
282 bool DicomDir::IsReadable()
283 {
284    if ( Filetype == Unknown )
285    {
286       gdcmWarningMacro( "Wrong filetype");
287       return false;
288    }
289    if ( !MetaElems )
290    {
291       gdcmWarningMacro( "Meta Elements missing in DicomDir");
292       return false;
293    }
294    if ( Patients.size() <= 0 )
295    {
296       gdcmWarningMacro( "NO Patient in DicomDir");
297       return false;
298    }
299
300    return true;
301 }
302
303 /**
304  * \brief   adds *the* Meta to a partially created DICOMDIR
305  */  
306 DicomDirMeta *DicomDir::NewMeta()
307 {
308    if ( MetaElems )
309       delete MetaElems;
310
311    DocEntry *entry = GetFirstEntry();
312    if ( entry )
313    { 
314       MetaElems = new DicomDirMeta(true); // true = empty
315
316       entry = GetFirstEntry();
317       while( entry )
318       {
319          if ( dynamic_cast<SeqEntry *>(entry) )
320             break;
321
322          RemoveEntry(entry);
323          MetaElems->AddEntry(entry);
324
325          entry = GetFirstEntry();
326       }
327    }
328    else  // after root directory parsing
329    {
330       MetaElems = new DicomDirMeta(false); // false = not empty
331    }
332    MetaElems->SetSQItemNumber(0); // To avoid further missprinting
333    return MetaElems;  
334 }
335
336 /**
337  * \brief   adds a new Patient (with the basic elements) to a partially created
338  *          DICOMDIR
339  */
340 DicomDirPatient *DicomDir::NewPatient()
341 {
342    DicomDirPatient *p = new DicomDirPatient();
343    AddPatientToEnd( p );
344    return p;
345 }
346
347 /**
348  * \brief   Remove all Patients
349  */
350 void DicomDir::ClearPatient()
351 {
352    for(ListDicomDirPatient::iterator cc = Patients.begin();
353                                      cc!= Patients.end();
354                                    ++cc)
355    {
356       delete *cc;
357    }
358    Patients.clear();
359 }
360
361 /**
362  * \brief   Get the first entry while visiting the DicomDirPatients
363  * \return  The first DicomDirPatient if found, otherwhise NULL
364  */ 
365 DicomDirPatient *DicomDir::GetFirstPatient()
366 {
367    ItPatient = Patients.begin();
368    if ( ItPatient != Patients.end() )
369       return *ItPatient;
370    return NULL;
371 }
372
373 /**
374  * \brief   Get the next entry while visiting the DicomDirPatients
375  * \note : meaningfull only if GetFirstEntry already called
376  * \return  The next DicomDirPatient if found, otherwhise NULL
377  */
378 DicomDirPatient *DicomDir::GetNextPatient()
379 {
380    gdcmAssertMacro (ItPatient != Patients.end());
381
382    ++ItPatient;
383    if ( ItPatient != Patients.end() )
384       return *ItPatient;
385    return NULL;
386 }
387
388 /**
389  * \brief  fills the whole structure, starting from a root Directory
390  */
391 void DicomDir::ParseDirectory()
392 {
393    CreateDicomDirChainedList( GetFileName() );
394    CreateDicomDir();
395 }
396
397 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg )
398 {
399    SetStartMethod(method,arg,NULL);
400 }
401
402 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg )
403 {
404    SetProgressMethod(method,arg,NULL);
405 }
406
407 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg )
408 {
409    SetEndMethod(method,arg,NULL);
410 }
411
412 /**
413  * \brief   Set the start method to call when the parsing of the
414  *          directory starts.
415  * @param   method Method to call
416  * @param   arg    Argument to pass to the method
417  * @param   argDelete    Argument 
418  * \warning In python : the arg parameter isn't considered
419  */
420 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg, 
421                                DicomDir::Method *argDelete )
422 {
423    if ( StartArg && StartMethodArgDelete )
424    {
425       StartMethodArgDelete( StartArg );
426    }
427
428    StartMethod          = method;
429    StartArg             = arg;
430    StartMethodArgDelete = argDelete;
431 }
432
433
434 /**
435  * \brief   Set the progress method to call when the parsing of the
436  *          directory progress
437  * @param   method Method to call
438  * @param   arg    Argument to pass to the method
439  * @param   argDelete    Argument  
440  * \warning In python : the arg parameter isn't considered
441  */
442 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg, 
443                                   DicomDir::Method *argDelete )
444 {
445    if ( ProgressArg && ProgressMethodArgDelete )
446    {
447       ProgressMethodArgDelete( ProgressArg );
448    }
449
450    ProgressMethod          = method;
451    ProgressArg             = arg;
452    ProgressMethodArgDelete = argDelete;
453 }
454
455 /**
456  * \brief   Set the end method to call when the parsing of the directory ends
457  * @param   method Method to call
458  * @param   arg    Argument to pass to the method
459  * @param   argDelete    Argument 
460  * \warning In python : the arg parameter isn't considered
461  */
462 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg, 
463                              DicomDir::Method *argDelete )
464 {
465    if ( EndArg && EndMethodArgDelete )
466    {
467       EndMethodArgDelete( EndArg );
468    }
469
470    EndMethod          = method;
471    EndArg             = arg;
472    EndMethodArgDelete = argDelete;
473 }
474
475 /**
476  * \brief   Set the method to delete the argument
477  *          The argument is destroyed when the method is changed or when the
478  *          class is destroyed
479  * @param   method Method to call to delete the argument
480  */
481 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method ) 
482 {
483    StartMethodArgDelete = method;
484 }
485
486 /**
487  * \brief   Set the method to delete the argument
488  *          The argument is destroyed when the method is changed or when the 
489  *          class is destroyed          
490  * @param   method Method to call to delete the argument
491  */
492 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method *method )
493 {
494    ProgressMethodArgDelete = method;
495 }
496
497 /**
498  * \brief   Set the method to delete the argument
499  *          The argument is destroyed when the method is changed or when
500  *          the class is destroyed
501  * @param   method Method to call to delete the argument
502  */
503 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
504 {
505    EndMethodArgDelete = method;
506 }
507
508 /**
509  * \brief    writes on disc a DICOMDIR
510  * \ warning does NOT add the missing elements in the header :
511  *           it's up to the user doing it !
512  * @param  fileName file to be written to 
513  * @return false only when fail to open
514  */
515  
516 bool DicomDir::Write(std::string const &fileName) 
517 {  
518    int i;
519    uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
520    uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
521
522    std::ofstream *fp = new std::ofstream(fileName.c_str(),  
523                                          std::ios::out | std::ios::binary);
524    if ( !fp ) 
525    {
526       gdcmWarningMacro("Failed to open(write) File: " << fileName.c_str());
527       return false;
528    }
529
530    char filePreamble[128];
531    memset(filePreamble, 0, 128);
532    fp->write(filePreamble, 128);
533    binary_write( *fp, "DICM");
534  
535    DicomDirMeta *ptrMeta = GetMeta();
536    ptrMeta->WriteContent(fp, ExplicitVR);
537    
538    // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
539    for(i=0;i<4;++i)
540    {
541       binary_write(*fp, sq[i]);
542    }
543         
544    for(ListDicomDirPatient::iterator cc  = Patients.begin();
545                                      cc != Patients.end();
546                                    ++cc )
547    {
548       (*cc)->WriteContent( fp, ExplicitVR );
549    }
550    
551    // force writing Sequence Delimitation Item
552    for(i=0;i<4;++i)
553    {
554       binary_write(*fp, sqt[i]);  // fffe e0dd ffff ffff 
555    }
556
557    fp->close();
558    delete fp;
559
560    return true;
561 }
562
563 /**
564  * \brief    Anonymize a DICOMDIR
565  * @return true 
566  */
567  
568 bool DicomDir::Anonymize() 
569 {
570    DataEntry *v;
571    // Something clever to be found to forge the Patient names
572    std::ostringstream s;
573    int i = 1;
574    for(ListDicomDirPatient::iterator cc = Patients.begin();
575                                      cc!= Patients.end();
576                                    ++cc)
577    {
578       s << i;
579       v = (*cc)->GetDataEntry(0x0010, 0x0010) ; // Patient's Name
580       if (v)
581       {
582          v->SetString(s.str());
583       }
584
585       v = (*cc)->GetDataEntry(0x0010, 0x0020) ; // Patient ID
586       if (v)
587       {
588          v->SetString(" ");
589       }
590
591       v = (*cc)->GetDataEntry(0x0010, 0x0030) ; // Patient's BirthDate
592       if (v)
593       {
594          v->SetString(" ");
595       }
596       s << "";
597       i++;
598    }
599    return true;
600 }
601
602 //-----------------------------------------------------------------------------
603 // Protected
604 /**
605  * \brief create a Document-like chained list from a root Directory 
606  * @param path entry point of the tree-like structure
607  */
608 void DicomDir::CreateDicomDirChainedList(std::string const &path)
609 {
610    CallStartMethod();
611    DirList dirList(path,1); // gets recursively the file list
612    unsigned int count = 0;
613    VectDocument list;
614    File *f;
615
616    DirListType fileList = dirList.GetFilenames();
617
618    for( DirListType::iterator it  = fileList.begin();
619                               it != fileList.end();
620                               ++it )
621    {
622       Progress = (float)(count+1)/(float)fileList.size();
623       CallProgressMethod();
624       if ( Abort )
625       {
626          break;
627       }
628
629       f = new File( );
630       f->SetLoadMode(LoadMode); // we allow user not to load Sequences, or Shadow
631                               //             groups, or ......
632       f->SetFileName( it->c_str() );
633    /*int res = */f->Load( );
634
635 //     if ( !f )
636 //     {
637 //         gdcmWarningMacro( "Failure in new gdcm::File " << it->c_str() );
638 //         continue;
639 //      }
640       
641       if ( f->IsReadable() )
642       {
643          // Add the file to the chained list:
644          list.push_back(f);
645          gdcmWarningMacro( "Readable " << it->c_str() );
646        }
647        else
648        {
649           delete f;
650        }
651        count++;
652    }
653    // sorts Patient/Study/Serie/
654    std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
655    
656    std::string tmp = dirList.GetDirName();      
657    //for each File of the chained list, add/update the Patient/Study/Serie/Image info
658    SetElements(tmp, list);
659    CallEndMethod();
660
661    for(VectDocument::iterator itDoc=list.begin();
662        itDoc!=list.end();
663        ++itDoc)
664    {
665       delete dynamic_cast<File *>(*itDoc);
666    }
667 }
668
669 /**
670  * \brief   CallStartMethod
671  */
672 void DicomDir::CallStartMethod()
673 {
674    Progress = 0.0f;
675    Abort    = false;
676    if ( StartMethod )
677    {
678       StartMethod( StartArg );
679    }
680 }
681
682 /**
683  * \brief   CallProgressMethod
684  */
685 void DicomDir::CallProgressMethod()
686 {
687    if ( ProgressMethod )
688    {
689       ProgressMethod( ProgressArg );
690    }
691 }
692
693 /**
694  * \brief   CallEndMethod
695  */
696 void DicomDir::CallEndMethod()
697 {
698    Progress = 1.0f;
699    if ( EndMethod )
700    {
701       EndMethod( EndArg );
702    }
703 }
704
705 //-----------------------------------------------------------------------------
706 // Private
707 /**
708  * \brief Sets all fields to NULL
709  */
710 void DicomDir::Initialize()
711 {
712    StartMethod             = NULL;
713    ProgressMethod          = NULL;
714    EndMethod               = NULL;
715    StartMethodArgDelete    = NULL;
716    ProgressMethodArgDelete = NULL;
717    EndMethodArgDelete      = NULL;
718    StartArg                = NULL;
719    ProgressArg             = NULL;
720    EndArg                  = NULL;
721
722    Progress = 0.0;
723    Abort = false;
724
725    MetaElems = NULL;   
726 }
727
728 /**
729  * \brief create a 'gdcm::DicomDir' from a DICOMDIR Header 
730  */
731 void DicomDir::CreateDicomDir()
732 {
733    // The SeqEntries of "Directory Record Sequence" are parsed. 
734    //  When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
735    //  1 - we save the beginning iterator
736    //  2 - we continue to parse
737    //  3 - we find an other tag
738    //       + we create the object for the precedent tag
739    //       + loop to 1 -
740    gdcmDebugMacro("Create DicomDir");
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     = DataEntry::New( 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       entry->Delete();
1149    }
1150 }
1151
1152 /**
1153  * \brief   Move the content of the source SQItem to the destination SQItem
1154  *          Only DocEntry's are moved
1155  * @param dst destination SQItem
1156  * @param src source SQItem
1157  */
1158 void DicomDir::MoveSQItem(DocEntrySet *dst,DocEntrySet *src)
1159
1160    DocEntry *entry;
1161
1162    entry = src->GetFirstEntry();
1163    while(entry)
1164    {
1165       src->RemoveEntry(entry);
1166       dst->AddEntry(entry);
1167       // we destroyed -> the current iterator is not longer valid
1168       entry = src->GetFirstEntry();
1169    }
1170 }
1171
1172 /**
1173  * \brief   compares two files
1174  */
1175 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
1176 {
1177    return *header1 < *header2;
1178 }
1179
1180 //-----------------------------------------------------------------------------
1181 // Print
1182 /**
1183  * \brief  Canonical Printer 
1184  * @param   os ostream we want to print in
1185  * @param indent Indentation string to be prepended during printing
1186  */
1187 void DicomDir::Print(std::ostream &os, std::string const & )
1188 {
1189    if ( MetaElems )
1190    {
1191       MetaElems->SetPrintLevel(PrintLevel);
1192       MetaElems->Print(os);   
1193    }   
1194    for(ListDicomDirPatient::iterator cc  = Patients.begin();
1195                                      cc != Patients.end();
1196                                    ++cc)
1197    {
1198      (*cc)->SetPrintLevel(PrintLevel);
1199      (*cc)->Print(os);
1200    }
1201 }
1202
1203 //-----------------------------------------------------------------------------
1204 } // end namespace gdcm