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