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