]> Creatis software - gdcm.git/blob - src/gdcmDicomDir.cxx
- Speed up DICOMDIR analyse
[gdcm.git] / src / gdcmDicomDir.cxx
1 /*=========================================================================
2   
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDicomDir.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/07/03 12:45:53 $
7   Version:   $Revision: 1.143 $
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       // A decent DICOMDIR has much more images than series,
706       // more series than studies, and so on.
707       // This is the right order to preform the tests
708
709       if ( v == "IMAGE " ) 
710       {
711          si = new DicomDirImage(true);
712          if ( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
713          {
714             delete si;
715             si = NULL;
716             gdcmErrorMacro( "Add AddImageToEnd failed");
717          }
718       }
719       else if ( v == "SERIES" )
720       {
721          si = new DicomDirSerie(true);
722          if ( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
723          {
724             delete si;
725             si = NULL;
726             gdcmErrorMacro( "Add AddSerieToEnd failed");
727          }
728       }
729       else if ( v == "STUDY " )
730       {
731          si = new DicomDirStudy(true);
732          if ( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
733          {
734             delete si;
735             si = NULL;
736             gdcmErrorMacro( "Add AddStudyToEnd failed");
737          }
738       }
739       else if ( v == "PATIENT " )
740       {
741          si = new DicomDirPatient(true);
742          if ( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
743          {
744             delete si;
745             si = NULL;
746             gdcmErrorMacro( "Add PatientToEnd failed");
747          }
748       }
749       else
750       {
751          // It was neither a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
752          // nor an 'IMAGE' SQItem. Skip to next item.
753          gdcmWarningMacro( " -------------------------------------------"
754          << "a non PATIENT/STUDY/SERIE/IMAGE SQItem was found : "
755          << v);
756
757         // FIXME : deal with other item types !
758         tmpSI=s->GetNextSQItem(); // To avoid infinite loop
759         continue;
760       }
761       if ( si )
762          MoveSQItem(si,tmpSI);
763
764       tmpSI=s->GetNextSQItem();
765    }
766    ClearEntry();
767 }
768
769 /**
770  * \brief  AddPatientToEnd 
771  * @param   dd SQ Item to enqueue to the DicomPatient chained List
772  */
773 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
774 {
775    Patients.push_back(dd);
776    return true;
777 }
778
779 /**
780  * \brief  AddStudyToEnd 
781  * @param   dd SQ Item to enqueue to the DicomDirStudy chained List
782  */
783 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
784 {
785    if ( Patients.size() > 0 )
786    {
787       ListDicomDirPatient::iterator itp = Patients.end();
788       itp--;
789       (*itp)->AddStudy(dd);
790       return true;
791    }
792    return false;
793 }
794
795 /**
796  * \brief  AddSerieToEnd 
797  * @param   dd SQ Item to enqueue to the DicomDirSerie chained List
798  */
799 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
800 {
801    if ( Patients.size() > 0 )
802    {
803       ListDicomDirPatient::iterator itp = Patients.end();
804       itp--;
805
806       DicomDirStudy *study = (*itp)->GetLastStudy();
807       if ( study )
808       {
809          study->AddSerie(dd);
810          return true;
811       }
812    }
813    return false;
814 }
815
816 /**
817  * \brief   AddImageToEnd
818  * @param   dd SQ Item to enqueue to the DicomDirImage chained List
819  */
820 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
821 {
822    if ( Patients.size() > 0 )
823    {
824       ListDicomDirPatient::iterator itp = Patients.end();
825       itp--;
826
827       DicomDirStudy *study = (*itp)->GetLastStudy();
828       if ( study )
829       {
830          DicomDirSerie *serie = study->GetLastSerie();
831          if ( serie )
832          {
833             serie->AddImage(dd);
834             return true;
835          }
836       }
837    }
838    return false;
839 }
840
841 /**
842  * \brief  for each Header of the chained list, 
843  *         add/update the Patient/Study/Serie/Image info 
844  * @param   path path of the root directory
845  * @param   list chained list of Headers
846  */
847 void DicomDir::SetElements(std::string const &path, VectDocument const &list)
848 {
849    ClearEntry();
850    ClearPatient();
851
852    std::string patPrevName         = "", patPrevID  = "";
853    std::string studPrevInstanceUID = "", studPrevID = "";
854    std::string serPrevInstanceUID  = "", serPrevID  = "";
855
856    std::string patCurName,         patCurID;
857    std::string studCurInstanceUID, studCurID;
858    std::string serCurInstanceUID,  serCurID;
859
860    bool first = true;
861    for( VectDocument::const_iterator it = list.begin();
862                                      it != list.end(); 
863                                    ++it )
864    {
865       // get the current file characteristics
866       patCurName         = (*it)->GetEntryValue(0x0010,0x0010);
867       patCurID           = (*it)->GetEntryValue(0x0010,0x0011);
868       studCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000d);
869       studCurID          = (*it)->GetEntryValue(0x0020,0x0010);
870       serCurInstanceUID  = (*it)->GetEntryValue(0x0020,0x000e);
871       serCurID           = (*it)->GetEntryValue(0x0020,0x0011);
872
873       if ( patCurName != patPrevName || patCurID != patPrevID || first )
874       {
875          SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
876          first = true;
877       }
878
879       // if new Study, deal with 'STUDY' Elements   
880       if ( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID 
881          || first )
882       {
883          SetElement(path, GDCM_DICOMDIR_STUDY, *it);
884          first = true;
885       }
886
887       // if new Serie, deal with 'SERIE' Elements   
888       if ( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
889          || first )
890       {
891          SetElement(path, GDCM_DICOMDIR_SERIE, *it);
892       }
893       
894       // Always Deal with 'IMAGE' Elements  
895       SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
896
897       patPrevName         = patCurName;
898       patPrevID           = patCurID;
899       studPrevInstanceUID = studCurInstanceUID;
900       studPrevID          = studCurID;
901       serPrevInstanceUID  = serCurInstanceUID;
902       serPrevID           = serCurID;
903       first = false;
904    }
905 }
906
907 /**
908  * \brief   adds to the HTable 
909  *          the Entries (Dicom Elements) corresponding to the given type
910  * @param   path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
911  * @param   type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
912  *          GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
913  * @param   header Header of the current file
914  */
915 void DicomDir::SetElement(std::string const &path, DicomDirType type,
916                           Document *header)
917 {
918    ListDicomDirElem elemList;
919    ListDicomDirElem::const_iterator it;
920    uint16_t tmpGr, tmpEl;
921    DictEntry *dictEntry;
922    ValEntry *entry;
923    std::string val;
924    SQItem *si;
925
926    switch( type )
927    {
928       case GDCM_DICOMDIR_IMAGE:
929          elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
930          si = new DicomDirImage(true);
931          if ( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
932          {
933             delete si;
934             gdcmErrorMacro( "Add ImageToEnd failed");
935          }
936          break;
937       case GDCM_DICOMDIR_SERIE:
938          elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
939          si = new DicomDirSerie(true);
940          if ( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
941          {
942             delete si;
943             gdcmErrorMacro( "Add SerieToEnd failed");
944          }
945          break;
946       case GDCM_DICOMDIR_STUDY:
947          elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
948          si = new DicomDirStudy(true);
949          if ( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
950          {
951             delete si;
952             gdcmErrorMacro( "Add StudyToEnd failed");
953          }
954          break;
955       case GDCM_DICOMDIR_PATIENT:
956          elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
957          si = new DicomDirPatient(true);
958          if ( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
959          {
960             delete si;
961             gdcmErrorMacro( "Add PatientToEnd failed");
962          }
963          break;
964       case GDCM_DICOMDIR_META:
965          elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
966          si = new DicomDirMeta(true);
967          if ( MetaElems )
968          {
969             delete MetaElems;
970             gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
971          }
972          MetaElems = static_cast<DicomDirMeta *>(si);
973          break;
974       default:
975          return;
976    }
977    // removed all the seems-to-be-useless stuff about Referenced Image Sequence
978    // to avoid further troubles
979    // imageElem 0008 1140 "" // Referenced Image Sequence
980    // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
981    // imageElem 0008 1150 "" // Referenced SOP Class UID    : to be set/forged later
982    // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
983    // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
984  
985    // FIXME : troubles found when it's a SeqEntry
986
987    // for all the relevant elements found in their own spot of the DicomDir.dic
988    for( it = elemList.begin(); it != elemList.end(); ++it)
989    {
990       tmpGr     = it->Group;
991       tmpEl     = it->Elem;
992       dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
993
994       entry     = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
995
996       entry->SetOffset(0); // just to avoid further missprinting
997
998       if ( header )
999       {
1000          // NULL when we Build Up (ex nihilo) a DICOMDIR
1001          //   or when we add the META elems
1002          val = header->GetEntryValue(tmpGr, tmpEl);
1003       }
1004       else
1005       {
1006          val = GDCM_UNFOUND;
1007       }
1008
1009       if ( val == GDCM_UNFOUND) 
1010       {
1011          if ( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
1012          {
1013            // force to the *end* File Name
1014            val = Util::GetName( path );
1015          }
1016          else if ( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
1017          {
1018             if ( header->GetFileName().substr(0, path.length()) != path )
1019             {
1020                gdcmWarningMacro( "The base path of file name is incorrect");
1021                val = header->GetFileName();
1022             }
1023             else
1024             {
1025                val = &(header->GetFileName().c_str()[path.length()]);
1026             }
1027          }
1028          else
1029          {
1030             val = it->Value;
1031          }
1032       }
1033       else
1034       {
1035          if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
1036             val = it->Value;
1037       }
1038
1039       entry->SetValue( val ); // troubles expected when vr=SQ ...
1040
1041       if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
1042       {
1043          gdcmWarningMacro("GDCM_DICOMDIR_META ?!? should never print that");
1044       }
1045       si->AddEntry(entry);
1046    }
1047 }
1048
1049 /**
1050  * \brief   Move the content of the source SQItem to the destination SQItem
1051  *          Only DocEntry's are moved
1052  * @param dst destination SQItem
1053  * @param src source SQItem
1054  */
1055 void DicomDir::MoveSQItem(DocEntrySet *dst,DocEntrySet *src)
1056 {
1057    DocEntry *entry;
1058
1059    entry = src->GetFirstEntry();
1060    while(entry)
1061    {
1062       src->RemoveEntryNoDestroy(entry);
1063       dst->AddEntry(entry);
1064       // we destroyed -> the current iterator is not longer valid
1065       entry = src->GetFirstEntry();
1066    }
1067 }
1068
1069 /**
1070  * \brief   compares two files
1071  */
1072 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
1073 {
1074    return *header1 < *header2;
1075 }
1076
1077 //-----------------------------------------------------------------------------
1078 // Print
1079 /**
1080  * \brief  Canonical Printer 
1081  * @param   os ostream we want to print in
1082  * @param indent Indentation string to be prepended during printing
1083  */
1084 void DicomDir::Print(std::ostream &os, std::string const & )
1085 {
1086    if ( MetaElems )
1087    {
1088       MetaElems->SetPrintLevel(PrintLevel);
1089       MetaElems->Print(os);   
1090    }   
1091    for(ListDicomDirPatient::iterator cc  = Patients.begin();
1092                                      cc != Patients.end();
1093                                    ++cc)
1094    {
1095      (*cc)->SetPrintLevel(PrintLevel);
1096      (*cc)->Print(os);
1097    }
1098 }
1099
1100 //-----------------------------------------------------------------------------
1101 } // end namespace gdcm