]> Creatis software - gdcm.git/blob - src/gdcmDicomDir.cxx
c12a9a6f13c99970bba07ff357267faa5b789b41
[gdcm.git] / src / gdcmDicomDir.cxx
1 /*=========================================================================
2   
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDicomDir.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/01/07 19:20:38 $
7   Version:   $Revision: 1.94 $
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 #include "gdcmDicomDir.h"
20 #include "gdcmDicomDirStudy.h"
21 #include "gdcmDicomDirSerie.h"
22 #include "gdcmDicomDirImage.h"
23 #include "gdcmDicomDirPatient.h"
24 #include "gdcmDicomDirMeta.h"
25 #include "gdcmDicomDirElement.h"
26 #include "gdcmDirList.h"
27 #include "gdcmUtil.h"
28 #include "gdcmDebug.h"
29 #include "gdcmGlobal.h"
30 #include "gdcmHeader.h"
31 #include "gdcmSeqEntry.h"
32 #include "gdcmSQItem.h"
33 #include "gdcmValEntry.h"
34
35 #include <fstream>
36 #include <string>
37 #include <algorithm>
38 #include <sys/types.h>
39
40 #ifdef _MSC_VER
41 #define getcwd _getcwd
42 #endif
43
44 #if defined( _MSC_VER) || defined(__BORLANDC__)
45    #include <direct.h>
46 #else
47    #include <unistd.h>
48 #endif
49
50 namespace gdcm 
51 {
52
53 //-----------------------------------------------------------------------------
54 //  For full DICOMDIR description, see:
55 //  PS 3.3-2003, pages 731-750
56 //-----------------------------------------------------------------------------
57 // Constructor / Destructor
58
59 /**
60  * \ingroup DicomDir
61  * \brief   Constructor : creates an empty DicomDir
62  */
63 DicomDir::DicomDir()
64    :Document( )
65
66    Initialize();  // sets all private fields to NULL
67    MetaElems = NewMeta();
68 }
69
70 /**
71  * \brief Constructor Parses recursively the directory and creates the DicomDir
72  *        or uses an already built DICOMDIR, depending on 'parseDir' value.
73  * @param fileName        name 
74  *                      - of the root directory (parseDir = true)
75  *                      - of the DICOMDIR       (parseDir = false)
76  * @param parseDir boolean
77  *                      - true if user passed an entry point 
78  *                        and wants to explore recursively the directories
79  *                      - false if user passed an already built DICOMDIR file
80  *                        and wants to use it 
81  */
82 DicomDir::DicomDir(std::string const &fileName, bool parseDir ):
83    Document( fileName )
84 {
85    // Whatever user passed (a root directory or a DICOMDIR)
86    // and whatever the value of parseDir was,
87    // Document is already executed
88    Initialize();  // sets all private fields to NULL
89
90    // if user passed a root directory, sure we didn't get anything
91    if ( TagHT.begin() == TagHT.end() ) // when user passed a Directory to parse
92    {
93       gdcmVerboseMacro("DicomDir::DicomDir : entry HT empty");
94
95       if ( fileName == "." )
96       {
97          // user passed '.' as Name
98          // we get current directory name
99          char dummy[1000];
100          getcwd(dummy, (size_t)1000);
101          SetFileName( dummy ); // will be converted into a string
102       }
103
104       if ( parseDir ) // user asked for a recursive parsing of a root directory
105       {
106          MetaElems = NewMeta();
107
108          gdcmVerboseMacro("DicomDir::DicomDir : Parse directory" 
109                      " and create the DicomDir");
110          ParseDirectory();
111       }
112       else
113       {
114          /// \todo if parseDir == false, it should be tagged as an error
115          // NON ! il suffit d'appeler ParseDirectory() 
116          // apres le constructeur
117       }
118    }
119    else // Only if user passed a DICOMDIR
120    {
121       // Directory record sequence
122       DocEntry *e = GetDocEntryByNumber(0x0004, 0x1220);
123       if ( !e )
124       {
125          gdcmVerboseMacro("DicomDir::DicomDir : NO Directory record"
126                         " sequence (0x0004,0x1220)");
127          /// \todo FIXME : what do we do when the parsed file IS NOT a
128          ///       DICOMDIR file ?         
129       }
130       else
131          CreateDicomDir();
132    }
133 }
134
135 /**
136  * \brief  Canonical destructor 
137  */
138 DicomDir::~DicomDir() 
139 {
140    SetStartMethod(NULL);
141    SetProgressMethod(NULL);
142    SetEndMethod(NULL);
143
144    for(ListDicomDirPatient::iterator cc = Patients.begin();
145                                      cc!= Patients.end();
146                                    ++cc)
147    {
148       delete *cc;
149    }
150    if ( MetaElems )
151    {
152       delete MetaElems;
153    }
154 }
155
156 //-----------------------------------------------------------------------------
157 // Print
158 /**
159  * \brief  Canonical Printer 
160  */
161 void DicomDir::Print(std::ostream &os)
162 {
163    if( MetaElems )
164    {
165       MetaElems->SetPrintLevel(PrintLevel);
166       MetaElems->Print(os);   
167    }   
168    for(ListDicomDirPatient::iterator cc  = Patients.begin();
169                                      cc != Patients.end();
170                                    ++cc)
171    {
172      (*cc)->SetPrintLevel(PrintLevel);
173      (*cc)->Print(os);
174    }
175 }
176
177 //-----------------------------------------------------------------------------
178 // Public
179 /**
180  * \brief  This predicate, based on hopefully reasonable heuristics,
181  *         decides whether or not the current header was properly parsed
182  *         and contains the mandatory information for being considered as
183  *         a well formed and usable DicomDir.
184  * @return true when Document is the one of a reasonable DicomDir,
185  *         false otherwise. 
186  */
187 bool DicomDir::IsReadable()
188 {
189    if( !Document::IsReadable() )
190    {
191       return false;
192    }
193    if( !MetaElems )
194    {
195       return false;
196    }
197    if( Patients.size() <= 0 )
198    {
199       return false;
200    }
201
202    return true;
203 }
204
205 /**
206  * \brief Sets all fields to NULL
207  */
208
209 void DicomDir::Initialize()
210 {
211    StartMethod             = NULL;
212    ProgressMethod          = NULL;
213    EndMethod               = NULL;
214    StartMethodArgDelete    = NULL;
215    ProgressMethodArgDelete = NULL;
216    EndMethodArgDelete      = NULL;
217    StartArg                = NULL;
218    ProgressArg             = NULL;
219    EndArg                  = NULL;
220
221    Progress = 0.0;
222    Abort = false;
223
224    MetaElems = NULL;   
225 }
226
227
228 /**
229  * \ingroup DicomDir
230  * \brief  fills the whole structure, starting from a root Directory
231  */
232 void DicomDir::ParseDirectory()
233 {
234    CreateDicomDirChainedList( GetFileName() );
235    CreateDicomDir();
236 }
237
238 /**
239  * \ingroup DicomDir
240  * \brief   Set the start method to call when the parsing of the
241  *          directory starts.
242  * @param   method Method to call
243  * @param   arg    Argument to pass to the method
244  * @param   argDelete    Argument 
245  * \warning In python : the arg parameter isn't considered
246  */
247 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg, 
248                                DicomDir::Method *argDelete )
249 {
250    if( StartArg && StartMethodArgDelete )
251    {
252       StartMethodArgDelete( StartArg );
253    }
254
255    StartMethod          = method;
256    StartArg             = arg;
257    StartMethodArgDelete = argDelete;
258 }
259
260 /**
261  * \ingroup DicomDir
262  * \brief   Set the method to delete the argument
263  *          The argument is destroyed when the method is changed or when the
264  *          class is destroyed
265  * @param   method Method to call to delete the argument
266  */
267 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method ) 
268 {
269    StartMethodArgDelete = method;
270 }
271
272 /**
273  * \ingroup DicomDir
274  * \brief   Set the progress method to call when the parsing of the
275  *          directory progress
276  * @param   method Method to call
277  * @param   arg    Argument to pass to the method
278  * @param   argDelete    Argument  
279  * \warning In python : the arg parameter isn't considered
280  */
281 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg, 
282                                   DicomDir::Method *argDelete )
283 {
284    if( ProgressArg && ProgressMethodArgDelete )
285    {
286       ProgressMethodArgDelete( ProgressArg );
287    }
288
289    ProgressMethod          = method;
290    ProgressArg             = arg;
291    ProgressMethodArgDelete = argDelete;
292 }
293
294 /**
295  * \ingroup DicomDir
296  * \brief   Set the method to delete the argument
297  *          The argument is destroyed when the method is changed or when the 
298  *          class is destroyed          
299  * @param   method Method to call to delete the argument
300  */
301 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method *method )
302 {
303    ProgressMethodArgDelete = method;
304 }
305
306 /**
307  * \ingroup DicomDir
308  * \brief   Set the end method to call when the parsing of the directory ends
309  * @param   method Method to call
310  * @param   arg    Argument to pass to the method
311  * @param   argDelete    Argument 
312  * \warning In python : the arg parameter isn't considered
313  */
314 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg, 
315                              DicomDir::Method *argDelete )
316 {
317    if( EndArg && EndMethodArgDelete )
318    {
319       EndMethodArgDelete( EndArg );
320    }
321
322    EndMethod          = method;
323    EndArg             = arg;
324    EndMethodArgDelete = argDelete;
325 }
326
327 /**
328  * \ingroup DicomDir
329  * \brief   Set the method to delete the argument
330  *          The argument is destroyed when the method is changed or when
331  *          the class is destroyed
332  * @param   method Method to call to delete the argument
333  */
334 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
335 {
336    EndMethodArgDelete = method;
337 }
338
339 /**
340  * \ingroup DicomDir
341  * \brief    writes on disc a DICOMDIR
342  * \ warning does NOT add the missing elements in the header :
343  *           it's up to the user doing it !
344  * \todo : to be re-written using the DICOMDIR tree-like structure
345  *         *not* the chained list
346  *         (does NOT exist if the DICOMDIR is user-forged !)
347  * @param  fileName file to be written to 
348  * @return false only when fail to open
349  */
350  
351 bool DicomDir::WriteDicomDir(std::string const &fileName) 
352 {  
353    int i;
354    uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
355    uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
356
357    std::ofstream *fp = new std::ofstream(fileName.c_str(),  
358                                          std::ios::out | std::ios::binary);
359    if( !fp ) 
360    {
361       gdcmVerboseMacro("Failed to open(write) File: " << fileName.c_str());
362       return false;
363    }
364
365    char filePreamble[128];
366    memset(filePreamble, 0, 128);
367    fp->write(filePreamble, 128); //FIXME
368    binary_write( *fp, "DICM");
369  
370    DicomDirMeta *ptrMeta = GetDicomDirMeta();
371    ptrMeta->WriteContent(fp, ExplicitVR);
372    
373    // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
374    for(i=0;i<4;++i)
375    {
376       binary_write(*fp, sq[i]);
377    }
378         
379    for(ListDicomDirPatient::iterator cc  = Patients.begin();
380                                      cc != Patients.end();
381                                    ++cc )
382    {
383       (*cc)->WriteContent( fp, ExplicitVR );
384    }
385    
386    // force writing Sequence Delimitation Item
387    for(i=0;i<4;++i)
388    {
389       binary_write(*fp, sqt[i]);  // fffe e0dd ffff ffff 
390    }
391
392    fp->close();
393    delete fp;
394
395    return true;
396 }
397
398 //-----------------------------------------------------------------------------
399 // Protected
400
401 /**
402  * \ingroup DicomDir
403  * \brief create a Document-like chained list from a root Directory 
404  * @param path entry point of the tree-like structure
405  */
406 void DicomDir::CreateDicomDirChainedList(std::string const & path)
407 {
408    CallStartMethod();
409    DirList fileList(path,1); // gets recursively the file list
410    unsigned int count = 0;
411    VectDocument list;
412    Header *header;
413
414    for( DirList::iterator it  = fileList.begin();
415                               it != fileList.end();
416                               ++it )
417    {
418       Progress = (float)(count+1)/(float)fileList.size();
419       CallProgressMethod();
420       if( Abort )
421       {
422          break;
423       }
424
425       header = new Header( it->c_str() );
426       if( !header )
427       {
428          gdcmVerboseMacro( "DicomDir::CreateDicomDirChainedList: " <<
429                       "failure in new Header " <<
430                       it->c_str() );
431          continue;
432       }
433       
434       if( header->IsReadable() )
435       {
436          // Add the file header to the chained list:
437          list.push_back(header);
438          gdcmVerboseMacro( "DicomDir::CreateDicomDirChainedList: readable " <<
439                       it->c_str() );
440        }
441        else
442        {
443           delete header;
444        }
445        count++;
446    }
447    // sorts Patient/Study/Serie/
448    std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
449    
450    std::string tmp = fileList.GetDirName();      
451    //for each Header of the chained list, add/update the Patient/Study/Serie/Image info
452    SetElements(tmp, list);
453    CallEndMethod();
454
455    for(VectDocument::iterator itDoc=list.begin();
456        itDoc!=list.end();
457        ++itDoc)
458    {
459       delete dynamic_cast<Header *>(*itDoc);
460    }
461 }
462
463 /**
464  * \ingroup DicomDir
465  * \brief   adds *the* Meta to a partially created DICOMDIR
466  */
467   
468 DicomDirMeta * DicomDir::NewMeta()
469 {
470    DicomDirMeta *m = new DicomDirMeta();
471   
472    if ( TagHT.begin() != TagHT.end() ) // after Document Parsing
473    { 
474       TagDocEntryHT::iterator lastOneButSequence = TagHT.end();
475       lastOneButSequence --;
476       // ALL the 'out of Sequence' Tags belong to Meta Elems
477       // (we skip 0004|1220 [Directory record sequence] )
478       for ( TagDocEntryHT::iterator cc  = TagHT.begin(); 
479                                     cc != lastOneButSequence;
480                                    ++cc)
481       {
482          m->AddEntry( cc->second );
483       }
484    }
485    else  // after root directory parsing
486    {
487       ListDicomDirMetaElem const &elemList = 
488          Global::GetDicomDirElements()->GetDicomDirMetaElements();
489       m->FillObject(elemList);
490    }
491    m->SetSQItemNumber(0); // To avoid further missprinting
492    return m;  
493 }
494
495 /**
496  * \brief   adds a new Patient (with the basic elements) to a partially created DICOMDIR
497  */
498 DicomDirPatient *DicomDir::NewPatient()
499 {
500    ListDicomDirPatientElem::const_iterator it;
501    uint16_t tmpGr,tmpEl;
502    DictEntry *dictEntry;
503    ValEntry *entry;
504
505    ListDicomDirPatientElem const & elemList =
506       Global::GetDicomDirElements()->GetDicomDirPatientElements(); 
507    DicomDirPatient *p = new DicomDirPatient();
508
509    // for all the DicomDirPatient Elements      
510    for( it = elemList.begin(); it != elemList.end(); ++it ) 
511    {
512       tmpGr     = it->Group;
513       tmpEl     = it->Elem;
514       dictEntry = GetPubDict()->GetDictEntryByNumber(tmpGr, tmpEl);
515       entry     = new ValEntry( dictEntry );
516       entry->SetOffset(0); // just to avoid further missprinting
517       entry->SetValue( it->Value );
518
519       p->AddEntry( entry );
520    }
521
522    Patients.push_front( p );
523
524    return p;
525 }
526
527 /**
528  * \brief   adds to the HTable 
529  *          the Entries (Dicom Elements) corresponding to the given type
530  * @param   path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
531  * @param   type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
532  *          GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
533  * @param   header Header of the current file
534  */
535 void DicomDir::SetElement(std::string const &path, DicomDirType type,
536                           Document *header)
537 {
538    ListDicomDirElem elemList; //FIXME this is going to be a by copy operation
539    ListDicomDirElem::const_iterator it;
540    uint16_t tmpGr, tmpEl;
541    DictEntry *dictEntry;
542    ValEntry *entry;
543    std::string val;
544    SQItem *si;
545
546    switch( type )
547    {
548       case GDCM_DICOMDIR_IMAGE:
549          elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
550          si = new DicomDirImage();
551          if( !AddDicomDirImageToEnd(static_cast<DicomDirImage *>(si)) )
552          {
553             gdcmVerboseMacro("DicomDir::SetElement:"
554                         "Add DicomDirImageToEnd failed");
555          }
556          break;
557       case GDCM_DICOMDIR_SERIE:
558          elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
559          si = new DicomDirSerie();
560          if( !AddDicomDirSerieToEnd(static_cast<DicomDirSerie *>(si)) )
561          {
562             gdcmVerboseMacro("DicomDir::SetElement:"
563                         "Add DicomDirSerieToEnd failed");
564          }
565          break;
566       case GDCM_DICOMDIR_STUDY:
567          elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
568          si = new DicomDirStudy();
569          if( !AddDicomDirStudyToEnd(static_cast<DicomDirStudy *>(si)) )
570          {
571             gdcmVerboseMacro("DicomDir::SetElement:"
572                         "Add DicomDirStudyToEnd failed");
573          }
574          break;
575       case GDCM_DICOMDIR_PATIENT:
576          elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
577          si = new DicomDirPatient();
578          if( !AddDicomDirPatientToEnd(static_cast<DicomDirPatient *>(si)) )
579          {
580             gdcmVerboseMacro("DicomDir::SetElement:"
581                         "Add DicomDirPatientToEnd failed");
582          }
583          break;
584       case GDCM_DICOMDIR_META:
585          elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
586          si = new DicomDirMeta();
587          if( MetaElems )
588          {
589             gdcmVerboseMacro("DicomDir::SetElement:"
590                         "MetaElements already exist, they will be destroyed");
591             delete MetaElems;
592          }
593          MetaElems = static_cast<DicomDirMeta *>(si);
594          break;
595       default:
596          return;
597    }
598    // removed all the seems-to-be-useless stuff about Referenced Image Sequence
599    // to avoid further troubles
600    // imageElem 0008 1140 "" // Referenced Image Sequence
601    // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
602    // imageElem 0008 1150 "" // Referenced SOP Class UID    : to be set/forged later
603    // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
604    // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
605    // for all the relevant elements found in their own spot of the DicomDir.dic
606    // FIXME : troubles found when it's a SeqEntry
607
608    for( it = elemList.begin(); it != elemList.end(); ++it)
609    {
610       tmpGr     = it->Group;
611       tmpEl     = it->Elem;
612       dictEntry = GetPubDict()->GetDictEntryByNumber(tmpGr, tmpEl);
613
614       entry     = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
615
616       entry->SetOffset(0); // just to avoid further missprinting
617
618       if( header )
619       {
620          // NULL when we Build Up (ex nihilo) a DICOMDIR
621          //   or when we add the META elems
622          val = header->GetEntryByNumber(tmpGr, tmpEl);
623       }
624       else
625       {
626          val = GDCM_UNFOUND;
627       }
628
629       if( val == GDCM_UNFOUND) 
630       {
631          if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
632          {
633            // force to the *end* File Name
634            val = Util::GetName( path );
635          }
636          else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
637          {
638             if( header->GetFileName().substr(0, path.length()) != path )
639             {
640                gdcmVerboseMacro("DicomDir::SetElement : the base path"
641                            " of file name is incorrect");
642                val = header->GetFileName();
643             }
644             else
645             {
646                val = &(header->GetFileName().c_str()[path.length()]);
647             }
648          }
649          else
650          {
651             val = it->Value;
652          }
653       }
654       else
655       {
656          if ( header->GetEntryLengthByNumber(tmpGr,tmpEl) == 0 )
657             val = it->Value;
658       }
659
660       entry->SetValue( val ); // troubles expected when vr=SQ ...
661
662       if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
663       {
664          std::cout << "GDCM_DICOMDIR_META ?!? should never print that" 
665                    << std::endl;
666       }
667       si->AddEntry(entry);
668    }
669 }
670
671 //-----------------------------------------------------------------------------
672 /**
673  * \brief   CallStartMethod
674  */
675 void DicomDir::CallStartMethod()
676 {
677    Progress = 0.0f;
678    Abort    = false;
679    if( StartMethod )
680    {
681       StartMethod( StartArg );
682    }
683 }
684
685 //-----------------------------------------------------------------------------
686 /**
687  * \ingroup DicomDir
688  * \brief   CallProgressMethod
689  */
690 void DicomDir::CallProgressMethod()
691 {
692    if( ProgressMethod )
693    {
694       ProgressMethod( ProgressArg );
695    }
696 }
697
698 //-----------------------------------------------------------------------------
699 /**
700  * \ingroup DicomDir
701  * \brief   CallEndMethod
702  */
703 void DicomDir::CallEndMethod()
704 {
705    Progress = 1.0f;
706    if( EndMethod )
707    {
708       EndMethod( EndArg );
709    }
710 }
711
712 //-----------------------------------------------------------------------------
713 // Private
714 /**
715  * \ingroup DicomDir
716  * \brief create a 'DicomDir' from a DICOMDIR Header 
717  */
718 void DicomDir::CreateDicomDir()
719 {
720    // The list is parsed. 
721    //  When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
722    //  1 - we save the beginning iterator
723    //  2 - we continue to parse
724    //  3 - we find an other tag
725    //       + we create the object for the precedent tag
726    //       + loop to 1 -
727
728    // Directory record sequence
729    DocEntry *e = GetDocEntryByNumber(0x0004, 0x1220);
730    if ( !e )
731    {
732       gdcmVerboseMacro("DicomDir::DicomDir : NO Directory record"
733                   " sequence (0x0004,0x1220)");
734       /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ? 
735       return;         
736    }
737    
738    SeqEntry *s = dynamic_cast<SeqEntry *>(e);
739    if ( !s )
740    {
741       gdcmVerboseMacro("DicomDir::CreateDicomDir: no SeqEntry present");
742       // useless : (0x0004,0x1220) IS a Sequence !
743       return;
744    }
745
746    DicomDirType type; // = DicomDir::GDCM_DICOMDIR_META;
747    MetaElems = NewMeta();
748
749    ListSQItem listItems = s->GetSQItems();
750    
751    DocEntry *d;
752    std::string v;
753    SQItem *si;
754    for( ListSQItem::iterator i = listItems.begin(); 
755                              i !=listItems.end(); ++i ) 
756    {
757       d = (*i)->GetDocEntryByNumber(0x0004, 0x1430); // Directory Record Type
758       if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
759       {
760          v = valEntry->GetValue();
761       }
762       else
763       {
764          gdcmVerboseMacro("DicomDir::CreateDicomDir: not a ValEntry.");
765          continue;
766       }
767
768       if( v == "PATIENT " )
769       {
770          si = new DicomDirPatient();
771          AddDicomDirPatientToEnd( static_cast<DicomDirPatient *>(si) );
772          type = DicomDir::GDCM_DICOMDIR_PATIENT;
773       }
774       else if( v == "STUDY " )
775       {
776          si = new DicomDirStudy();
777          AddDicomDirStudyToEnd( static_cast<DicomDirStudy *>(si) );
778          type = DicomDir::GDCM_DICOMDIR_STUDY;
779       }
780       else if( v == "SERIES" )
781       {
782          si = new DicomDirSerie();
783          AddDicomDirSerieToEnd( static_cast<DicomDirSerie *>(si) );
784          type = DicomDir::GDCM_DICOMDIR_SERIE;
785       }
786       else if( v == "IMAGE " ) 
787       {
788          si = new DicomDirImage();
789          AddDicomDirImageToEnd( static_cast<DicomDirImage *>(si) );
790          type = DicomDir::GDCM_DICOMDIR_IMAGE;
791       }
792       else
793       {
794          // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
795          // neither an 'IMAGE' SQItem. Skip to next item.
796          continue;
797       }
798       MoveSQItem(si,*i);
799    }
800    TagHT.clear();
801 }
802
803 /**
804  * \ingroup DicomDir
805  * \brief Well ... there is only one occurence  
806  */
807 bool DicomDir::AddDicomDirMeta()
808 {
809    if( MetaElems )
810    {
811       delete MetaElems;
812    }
813    MetaElems = new DicomDirMeta();
814    return true;
815 }
816
817 /**
818  * \ingroup DicomDir
819  * \brief  AddDicomDirPatientToEnd 
820  * @param   dd SQ Item to enqueue to the DicomPatient chained List
821  */
822 bool DicomDir::AddDicomDirPatientToEnd(DicomDirPatient *dd)
823 {
824    Patients.push_back(dd);
825    return true;
826 }
827
828 /**
829  * \ingroup DicomDir
830  * \brief  AddDicomDirStudyToEnd 
831  * @param   dd SQ Item to enqueue to the DicomDirStudy chained List
832  */
833 bool DicomDir::AddDicomDirStudyToEnd(DicomDirStudy *dd)
834 {
835    if( Patients.size() > 0 )
836    {
837       ListDicomDirPatient::iterator itp = Patients.end();
838       itp--;
839       (*itp)->AddDicomDirStudy(dd);
840       return true;
841    }
842    return false;
843 }
844
845 /**
846  * \ingroup DicomDir
847  * \brief  AddDicomDirSerieToEnd 
848  * @param   dd SQ Item to enqueue to the DicomDirSerie chained List
849  */
850 bool DicomDir::AddDicomDirSerieToEnd(DicomDirSerie *dd)
851 {
852    if( Patients.size() > 0 )
853    {
854       ListDicomDirPatient::iterator itp = Patients.end();
855       itp--;
856
857       if( (*itp)->GetDicomDirStudies().size() > 0 )
858       {
859          ListDicomDirStudy::const_iterator itst = 
860             (*itp)->GetDicomDirStudies().end();
861          itst--;
862          (*itst)->AddDicomDirSerie(dd);
863          return true;
864       }
865    }
866    return false;
867 }
868
869 /**
870  * \ingroup DicomDir
871  * \brief   AddDicomDirImageToEnd
872  * @param   dd SQ Item to enqueue to the DicomDirImage chained List
873  */
874 bool DicomDir::AddDicomDirImageToEnd(DicomDirImage *dd)
875 {
876    if( Patients.size() > 0 )
877    {
878       ListDicomDirPatient::iterator itp = Patients.end();
879       itp--;
880
881       if( (*itp)->GetDicomDirStudies().size() > 0 )
882       {
883          ListDicomDirStudy::const_iterator itst = 
884             (*itp)->GetDicomDirStudies().end();
885          itst--;
886
887          if( (*itst)->GetDicomDirSeries().size() > 0 )
888          {
889             ListDicomDirSerie::const_iterator its = (*itst)->GetDicomDirSeries().end();
890             its--;
891             (*its)->AddDicomDirImage(dd);
892             return true;
893          }
894       }
895    }
896    return false;
897 }
898
899 /**
900  * \ingroup DicomDir
901  * \brief  for each Header of the chained list, add/update the Patient/Study/Serie/Image info 
902  * @param   path path of the root directory
903  * @param   list chained list of Headers
904  */
905 void DicomDir::SetElements(std::string const & path, VectDocument const &list)
906 {
907    TagHT.clear();
908    Patients.clear();
909
910    std::string patPrevName         = "", patPrevID  = "";
911    std::string studPrevInstanceUID = "", studPrevID = "";
912    std::string serPrevInstanceUID  = "", serPrevID  = "";
913
914    std::string patCurName,         patCurID;
915    std::string studCurInstanceUID, studCurID;
916    std::string serCurInstanceUID,  serCurID;
917
918    bool first = true;
919    for( VectDocument::const_iterator it = list.begin();
920                                      it != list.end(); ++it )
921    {
922       // get the current file characteristics
923       patCurName         = (*it)->GetEntryByNumber(0x0010,0x0010);
924       patCurID           = (*it)->GetEntryByNumber(0x0010,0x0011);
925       studCurInstanceUID = (*it)->GetEntryByNumber(0x0020,0x000d);
926       studCurID          = (*it)->GetEntryByNumber(0x0020,0x0010);
927       serCurInstanceUID  = (*it)->GetEntryByNumber(0x0020,0x000e);
928       serCurID           = (*it)->GetEntryByNumber(0x0020,0x0011);
929
930       if( patCurName != patPrevName || patCurID != patPrevID || first )
931       {
932          SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
933          first = true;
934       }
935
936       // if new Study Deal with 'STUDY' Elements   
937       if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID 
938          || first )
939       {
940          SetElement(path, GDCM_DICOMDIR_STUDY, *it);
941          first = true;
942       }
943
944       // if new Serie Deal with 'SERIE' Elements   
945       if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
946          || first )
947       {
948          SetElement(path, GDCM_DICOMDIR_SERIE, *it);
949          first = true;
950       }
951       
952       // Always Deal with 'IMAGE' Elements  
953       SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
954
955       patPrevName         = patCurName;
956       patPrevID           = patCurID;
957       studPrevInstanceUID = studCurInstanceUID;
958       studPrevID          = studCurID;
959       serPrevInstanceUID  = serCurInstanceUID;
960       serPrevID           = serCurID;
961       first = false;
962    }
963 }
964
965 /**
966  * \ingroup DicomDir
967  * \brief   Move the content of the src SQItem to the dst SQItem
968  *          Only DocEntry's are moved
969  * 
970  */
971 void DicomDir::MoveSQItem(SQItem *dst,SQItem *src)
972 {
973    DocEntry *entry;
974
975    src->Initialize();
976    entry = src->GetNextEntry();
977    while(entry)
978    {
979       src->RemoveEntryNoDestroy(entry);
980       dst->AddEntry(entry);
981
982       src->Initialize();
983       entry = src->GetNextEntry();
984    }
985 }
986
987 /**
988  * \ingroup DicomDir
989  * \brief   compares two dgcmHeaders
990  */
991 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
992 {
993    return *header1 < *header2;
994 }
995 } // end namespace gdcm
996
997 //-----------------------------------------------------------------------------