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