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