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