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