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