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