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