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