]> Creatis software - gdcm.git/blob - src/gdcmDicomDir.cxx
To speed up DicomDir, instead of copying -and removing the source afterwards-
[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 17:08:12 $
7   Version:   $Revision: 1.148 $
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->Load( it->c_str() );
612
613 //     if ( !f )
614 //     {
615 //         gdcmWarningMacro( "Failure in new gdcm::File " << it->c_str() );
616 //         continue;
617 //      }
618       
619       if ( f->IsReadable() )
620       {
621          // Add the file to the chained list:
622          list.push_back(f);
623          gdcmWarningMacro( "Readable " << it->c_str() );
624        }
625        else
626        {
627           delete f;
628        }
629        count++;
630    }
631    // sorts Patient/Study/Serie/
632    std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
633    
634    std::string tmp = dirList.GetDirName();      
635    //for each File of the chained list, add/update the Patient/Study/Serie/Image info
636    SetElements(tmp, list);
637    CallEndMethod();
638
639    for(VectDocument::iterator itDoc=list.begin();
640        itDoc!=list.end();
641        ++itDoc)
642    {
643       delete dynamic_cast<File *>(*itDoc);
644    }
645 }
646
647 /**
648  * \brief   CallStartMethod
649  */
650 void DicomDir::CallStartMethod()
651 {
652    Progress = 0.0f;
653    Abort    = false;
654    if ( StartMethod )
655    {
656       StartMethod( StartArg );
657    }
658 }
659
660 /**
661  * \brief   CallProgressMethod
662  */
663 void DicomDir::CallProgressMethod()
664 {
665    if ( ProgressMethod )
666    {
667       ProgressMethod( ProgressArg );
668    }
669 }
670
671 /**
672  * \brief   CallEndMethod
673  */
674 void DicomDir::CallEndMethod()
675 {
676    Progress = 1.0f;
677    if ( EndMethod )
678    {
679       EndMethod( EndArg );
680    }
681 }
682
683 //-----------------------------------------------------------------------------
684 // Private
685 /**
686  * \brief Sets all fields to NULL
687  */
688 void DicomDir::Initialize()
689 {
690    StartMethod             = NULL;
691    ProgressMethod          = NULL;
692    EndMethod               = NULL;
693    StartMethodArgDelete    = NULL;
694    ProgressMethodArgDelete = NULL;
695    EndMethodArgDelete      = NULL;
696    StartArg                = NULL;
697    ProgressArg             = NULL;
698    EndArg                  = NULL;
699
700    Progress = 0.0;
701    Abort = false;
702
703    MetaElems = NULL;   
704 }
705
706 /**
707  * \brief create a 'gdcm::DicomDir' from a DICOMDIR Header 
708  */
709 void DicomDir::CreateDicomDir()
710 {
711    // The SeqEntries of "Directory Record Sequence" are parsed. 
712    //  When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
713    //  1 - we save the beginning iterator
714    //  2 - we continue to parse
715    //  3 - we find an other tag
716    //       + we create the object for the precedent tag
717    //       + loop to 1 -
718
719    // Directory record sequence
720    DocEntry *e = GetDocEntry(0x0004, 0x1220);
721    if ( !e )
722    {
723       gdcmWarningMacro( "No Directory Record Sequence (0004,1220) found");
724       return;         
725    }
726    
727    SeqEntry *s = dynamic_cast<SeqEntry *>(e);
728    if ( !s )
729    {
730       gdcmWarningMacro( "Element (0004,1220) is not a Sequence ?!?");
731       return;
732    }
733
734    NewMeta();
735    
736    DocEntry *d;
737    std::string v;
738    SQItem *si;
739
740    SQItem *tmpSI=s->GetFirstSQItem();
741    while(tmpSI)
742    {
743       d = tmpSI->GetDocEntry(0x0004, 0x1430); // Directory Record Type
744       if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
745       {
746          v = valEntry->GetValue();
747       }
748       else
749       {
750          gdcmWarningMacro( "(0004,1430) not a ValEntry ?!?");
751          continue;
752       }
753
754       // A decent DICOMDIR has much more images than series,
755       // more series than studies, and so on.
756       // This is the right order to preform the tests
757
758       if ( v == "IMAGE " ) 
759       {
760          si = new DicomDirImage(true);
761          if ( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
762          {
763             delete si;
764             si = NULL;
765             gdcmErrorMacro( "Add AddImageToEnd failed");
766          }
767       }
768       else if ( v == "SERIES" )
769       {
770          si = new DicomDirSerie(true);
771          if ( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
772          {
773             delete si;
774             si = NULL;
775             gdcmErrorMacro( "Add AddSerieToEnd failed");
776          }
777       }
778       else if ( v == "VISIT " )
779       {
780          si = new DicomDirVisit(true);
781          if ( !AddVisitToEnd( static_cast<DicomDirVisit *>(si)) )
782          {
783             delete si;
784             si = NULL;
785             gdcmErrorMacro( "Add AddVisitToEnd failed");
786          }
787       }
788       else if ( v == "STUDY " )
789       {
790          si = new DicomDirStudy(true);
791          if ( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
792          {
793             delete si;
794             si = NULL;
795             gdcmErrorMacro( "Add AddStudyToEnd failed");
796          }
797       }
798       else if ( v == "PATIENT " )
799       {
800          si = new DicomDirPatient(true);
801          if ( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
802          {
803             delete si;
804             si = NULL;
805             gdcmErrorMacro( "Add PatientToEnd failed");
806          }
807       }
808       else
809       {
810          // It was neither a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
811          // nor an 'IMAGE' SQItem. Skip to next item.
812          gdcmWarningMacro( " -------------------------------------------"
813          << "a non PATIENT/STUDY/SERIE/IMAGE SQItem was found : "
814          << v);
815
816         // FIXME : deal with other item types !
817         tmpSI=s->GetNextSQItem(); // To avoid infinite loop
818         continue;
819       }
820       if ( si )
821          //MoveSQItem(si,tmpSI); // Old code : Copies each Entry
822                                  //  -and then removes the source-
823          si->MoveObject(tmpSI);  // New code : Copies the List
824
825       tmpSI=s->GetNextSQItem();
826    }
827    ClearEntry();
828 }
829
830 /**
831  * \brief  AddPatientToEnd 
832  * @param   dd SQ Item to enqueue to the DicomPatient chained List
833  */
834 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
835 {
836    Patients.push_back(dd);
837    return true;
838 }
839
840 /**
841  * \brief  AddStudyToEnd 
842  * @param   dd SQ Item to enqueue to the DicomDirStudy chained List
843  */
844 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
845 {
846    if ( Patients.size() > 0 )
847    {
848       ListDicomDirPatient::iterator itp = Patients.end();
849       itp--;
850       (*itp)->AddStudy(dd);
851       return true;
852    }
853    return false;
854 }
855
856 /**
857  * \brief  AddSerieToEnd 
858  * @param   dd SQ Item to enqueue to the DicomDirSerie chained List
859  */
860 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
861 {
862    if ( Patients.size() > 0 )
863    {
864       ListDicomDirPatient::iterator itp = Patients.end();
865       itp--;
866
867       DicomDirStudy *study = (*itp)->GetLastStudy();
868       if ( study )
869       {
870          study->AddSerie(dd);
871          return true;
872       }
873    }
874    return false;
875 }
876
877 /**
878  * \brief  AddVisitToEnd 
879  * @param   dd SQ Item to enqueue to the DicomDirVisit chained List
880  */
881 bool DicomDir::AddVisitToEnd(DicomDirVisit *dd)
882 {
883    if ( Patients.size() > 0 )
884    {
885       ListDicomDirPatient::iterator itp = Patients.end();
886       itp--;
887
888       DicomDirStudy *study = (*itp)->GetLastStudy();
889       if ( study )
890       {
891          study->AddVisit(dd);
892          return true;
893       }
894    }
895    return false;
896 }
897 /**
898  * \brief   AddImageToEnd
899  * @param   dd SQ Item to enqueue to the DicomDirImage chained List
900  */
901 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
902 {
903    if ( Patients.size() > 0 )
904    {
905       ListDicomDirPatient::iterator itp = Patients.end();
906       itp--;
907
908       DicomDirStudy *study = (*itp)->GetLastStudy();
909       if ( study )
910       {
911          DicomDirSerie *serie = study->GetLastSerie();
912          if ( serie )
913          {
914             serie->AddImage(dd);
915             return true;
916          }
917       }
918    }
919    return false;
920 }
921
922 /**
923  * \brief  for each Header of the chained list, 
924  *         add/update the Patient/Study/Serie/Image info 
925  * @param   path path of the root directory
926  * @param   list chained list of Headers
927  */
928 void DicomDir::SetElements(std::string const &path, VectDocument const &list)
929 {
930    ClearEntry();
931    ClearPatient();
932
933    std::string patPrevName         = "", patPrevID  = "";
934    std::string studPrevInstanceUID = "", studPrevID = "";
935    std::string serPrevInstanceUID  = "", serPrevID  = "";
936
937    std::string patCurName,         patCurID;
938    std::string studCurInstanceUID, studCurID;
939    std::string serCurInstanceUID,  serCurID;
940
941    bool first = true;
942    for( VectDocument::const_iterator it = list.begin();
943                                      it != list.end(); 
944                                    ++it )
945    {
946       // get the current file characteristics
947       patCurName         = (*it)->GetEntryValue(0x0010,0x0010);
948       patCurID           = (*it)->GetEntryValue(0x0010,0x0011);
949       studCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000d);
950       studCurID          = (*it)->GetEntryValue(0x0020,0x0010);
951       serCurInstanceUID  = (*it)->GetEntryValue(0x0020,0x000e);
952       serCurID           = (*it)->GetEntryValue(0x0020,0x0011);
953
954       if ( patCurName != patPrevName || patCurID != patPrevID || first )
955       {
956          SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
957          first = true;
958       }
959
960       // if new Study, deal with 'STUDY' Elements   
961       if ( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID 
962          || first )
963       {
964          SetElement(path, GDCM_DICOMDIR_STUDY, *it);
965          first = true;
966       }
967
968       // if new Serie, deal with 'SERIE' Elements   
969       if ( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
970          || first )
971       {
972          SetElement(path, GDCM_DICOMDIR_SERIE, *it);
973       }
974       
975       // Always Deal with 'IMAGE' Elements  
976       SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
977
978       patPrevName         = patCurName;
979       patPrevID           = patCurID;
980       studPrevInstanceUID = studCurInstanceUID;
981       studPrevID          = studCurID;
982       serPrevInstanceUID  = serCurInstanceUID;
983       serPrevID           = serCurID;
984       first = false;
985    }
986 }
987
988 /**
989  * \brief   adds to the HTable 
990  *          the Entries (Dicom Elements) corresponding to the given type
991  * @param   path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
992  * @param   type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
993  *          GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
994  * @param   header Header of the current file
995  */
996 void DicomDir::SetElement(std::string const &path, DicomDirType type,
997                           Document *header)
998 {
999    ListDicomDirElem elemList;
1000    ListDicomDirElem::const_iterator it;
1001    uint16_t tmpGr, tmpEl;
1002    DictEntry *dictEntry;
1003    ValEntry *entry;
1004    std::string val;
1005    SQItem *si;
1006
1007    switch( type )
1008    {
1009       case GDCM_DICOMDIR_IMAGE:
1010          elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
1011          si = new DicomDirImage(true);
1012          if ( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
1013          {
1014             delete si;
1015             gdcmErrorMacro( "Add ImageToEnd failed");
1016          }
1017          break;
1018       case GDCM_DICOMDIR_SERIE:
1019          elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
1020          si = new DicomDirSerie(true);
1021          if ( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
1022          {
1023             delete si;
1024             gdcmErrorMacro( "Add SerieToEnd failed");
1025          }
1026          break;
1027       case GDCM_DICOMDIR_STUDY:
1028          elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
1029          si = new DicomDirStudy(true);
1030          if ( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
1031          {
1032             delete si;
1033             gdcmErrorMacro( "Add StudyToEnd failed");
1034          }
1035          break;
1036       case GDCM_DICOMDIR_PATIENT:
1037          elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
1038          si = new DicomDirPatient(true);
1039          if ( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
1040          {
1041             delete si;
1042             gdcmErrorMacro( "Add PatientToEnd failed");
1043          }
1044          break;
1045       case GDCM_DICOMDIR_META:
1046          elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
1047          si = new DicomDirMeta(true);
1048          if ( MetaElems )
1049          {
1050             delete MetaElems;
1051             gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
1052          }
1053          MetaElems = static_cast<DicomDirMeta *>(si);
1054          break;
1055       default:
1056          return;
1057    }
1058    // removed all the seems-to-be-useless stuff about Referenced Image Sequence
1059    // to avoid further troubles
1060    // imageElem 0008 1140 "" // Referenced Image Sequence
1061    // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
1062    // imageElem 0008 1150 "" // Referenced SOP Class UID    : to be set/forged later
1063    // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
1064    // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
1065  
1066    // FIXME : troubles found when it's a SeqEntry
1067
1068    // for all the relevant elements found in their own spot of the DicomDir.dic
1069    for( it = elemList.begin(); it != elemList.end(); ++it)
1070    {
1071       tmpGr     = it->Group;
1072       tmpEl     = it->Elem;
1073       dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
1074
1075       entry     = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
1076
1077       entry->SetOffset(0); // just to avoid further missprinting
1078
1079       if ( header )
1080       {
1081          // NULL when we Build Up (ex nihilo) a DICOMDIR
1082          //   or when we add the META elems
1083          val = header->GetEntryValue(tmpGr, tmpEl);
1084       }
1085       else
1086       {
1087          val = GDCM_UNFOUND;
1088       }
1089
1090       if ( val == GDCM_UNFOUND) 
1091       {
1092          if ( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
1093          {
1094            // force to the *end* File Name
1095            val = Util::GetName( path );
1096          }
1097          else if ( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
1098          {
1099             if ( header->GetFileName().substr(0, path.length()) != path )
1100             {
1101                gdcmWarningMacro( "The base path of file name is incorrect");
1102                val = header->GetFileName();
1103             }
1104             else
1105             {
1106                val = &(header->GetFileName().c_str()[path.length()]);
1107             }
1108          }
1109          else
1110          {
1111             val = it->Value;
1112          }
1113       }
1114       else
1115       {
1116          if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
1117             val = it->Value;
1118       }
1119
1120       entry->SetValue( val ); // troubles expected when vr=SQ ...
1121
1122       if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
1123       {
1124          gdcmWarningMacro("GDCM_DICOMDIR_META ?!? should never print that");
1125       }
1126       si->AddEntry(entry);
1127    }
1128 }
1129
1130 /**
1131  * \brief   Move the content of the source SQItem to the destination SQItem
1132  *          Only DocEntry's are moved
1133  * @param dst destination SQItem
1134  * @param src source SQItem
1135  */
1136 void DicomDir::MoveSQItem(DocEntrySet *dst,DocEntrySet *src)
1137
1138    DocEntry *entry;
1139
1140    entry = src->GetFirstEntry();
1141    while(entry)
1142    {
1143       src->RemoveEntryNoDestroy(entry);
1144       dst->AddEntry(entry);
1145       // we destroyed -> the current iterator is not longer valid
1146       entry = src->GetFirstEntry();
1147    }
1148 }
1149
1150 /**
1151  * \brief   compares two files
1152  */
1153 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
1154 {
1155    return *header1 < *header2;
1156 }
1157
1158 //-----------------------------------------------------------------------------
1159 // Print
1160 /**
1161  * \brief  Canonical Printer 
1162  * @param   os ostream we want to print in
1163  * @param indent Indentation string to be prepended during printing
1164  */
1165 void DicomDir::Print(std::ostream &os, std::string const & )
1166 {
1167    if ( MetaElems )
1168    {
1169       MetaElems->SetPrintLevel(PrintLevel);
1170       MetaElems->Print(os);   
1171    }   
1172    for(ListDicomDirPatient::iterator cc  = Patients.begin();
1173                                      cc != Patients.end();
1174                                    ++cc)
1175    {
1176      (*cc)->SetPrintLevel(PrintLevel);
1177      (*cc)->Print(os);
1178    }
1179 }
1180
1181 //-----------------------------------------------------------------------------
1182 } // end namespace gdcm