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