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