]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
Normalization
[gdcm.git] / src / gdcmDocument.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDocument.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/02/02 10:02:17 $
7   Version:   $Revision: 1.219 $
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 "gdcmDocument.h"
20 #include "gdcmValEntry.h"
21 #include "gdcmBinEntry.h"
22 #include "gdcmSeqEntry.h"
23 #include "gdcmGlobal.h"
24 #include "gdcmUtil.h"
25 #include "gdcmDebug.h"
26 #include "gdcmTS.h"
27 #include "gdcmDictSet.h"
28 #include "gdcmDocEntrySet.h"
29 #include "gdcmSQItem.h"
30
31 #include <vector>
32 #include <iomanip>
33
34 // For nthos:
35 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__) 
36    #include <winsock.h>
37 #endif
38
39 #ifdef CMAKE_HAVE_NETINET_IN_H
40    #include <netinet/in.h>
41 #endif
42
43 namespace gdcm 
44 {
45 //-----------------------------------------------------------------------------
46 // Refer to Document::CheckSwap()
47 //const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
48
49 // Refer to Document::SetMaxSizeLoadEntry()
50 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
51 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
52
53 //-----------------------------------------------------------------------------
54 // Constructor / Destructor
55 // Constructors and destructors are protected to avoid user to invoke directly
56 /**
57  * \brief   constructor  
58  * @param   filename 'Document' (File or DicomDir) to be opened for parsing
59  */
60 Document::Document( std::string const &filename ) 
61          :ElementSet(-1)
62 {
63    SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE); 
64    Filename = filename;
65    Initialize();
66
67    Fp = 0;
68    if ( !OpenFile() )
69    {
70       return;
71    }
72
73    Group0002Parsed = false;
74
75    gdcmVerboseMacro( "Starting parsing of file: " << Filename.c_str());
76   // Fp->seekg( 0,  std::ios::beg);
77    
78    Fp->seekg(0, std::ios::end);
79    long lgt = Fp->tellg();
80            
81    Fp->seekg(0, std::ios::beg);
82
83    CheckSwap();
84    long beg = Fp->tellg();
85    lgt -= beg;
86    
87    ParseDES( this, beg, lgt, false); // Loading is done during parsing
88
89    Fp->seekg( 0,  std::ios::beg);
90    
91    // Load 'non string' values
92       
93    std::string PhotometricInterpretation = GetEntryValue(0x0028,0x0004);   
94    if( PhotometricInterpretation == "PALETTE COLOR " )
95    {
96       LoadEntryBinArea(0x0028,0x1200);  // gray LUT   
97       /// FIXME FIXME FIXME
98       /// The tags refered by the three following lines used to be CORRECTLY
99       /// defined as having an US Value Representation in the public
100       /// dictionary. BUT the semantics implied by the three following
101       /// lines state that the corresponding tag contents are in fact
102       /// the ones of a BinEntry.
103       /// In order to fix things "Quick and Dirty" the dictionary was
104       /// altered on PURPOSE but now contains a WRONG value.
105       /// In order to fix things and restore the dictionary to its
106       /// correct value, one needs to decided of the semantics by deciding
107       /// whether the following tags are either:
108       /// - multivaluated US, and hence loaded as ValEntry, but afterwards
109       ///   also used as BinEntry, which requires the proper conversion,
110       /// - OW, and hence loaded as BinEntry, but afterwards also used
111       ///   as ValEntry, which requires the proper conversion.
112       LoadEntryBinArea(0x0028,0x1201);  // R    LUT
113       LoadEntryBinArea(0x0028,0x1202);  // G    LUT
114       LoadEntryBinArea(0x0028,0x1203);  // B    LUT
115       
116       // Segmented Red   Palette Color LUT Data
117       LoadEntryBinArea(0x0028,0x1221);
118       // Segmented Green Palette Color LUT Data
119       LoadEntryBinArea(0x0028,0x1222);
120       // Segmented Blue  Palette Color LUT Data
121       LoadEntryBinArea(0x0028,0x1223);
122    } 
123    //FIXME later : how to use it?
124    LoadEntryBinArea(0x0028,0x3006);  //LUT Data (CTX dependent) 
125
126    CloseFile(); 
127   
128    // ----------------------------
129    // Specific code to allow gdcm to read ACR-LibIDO formated images
130    // Note: ACR-LibIDO is an extension of the ACR standard that was
131    //       used at CREATIS. For the time being (say a couple years)
132    //       we keep this kludge to allow a smooth move to gdcm for
133    //       CREATIS developpers (sorry folks).
134    //
135    // if recognition code tells us we deal with a LibIDO image
136    // we switch lineNumber and columnNumber
137    //
138    std::string RecCode;
139    RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
140    if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
141        RecCode == "CANRME_AILIBOD1_1." )  // for brain-damaged softwares
142                                           // with "little-endian strings"
143    {
144          Filetype = ACR_LIBIDO; 
145          std::string rows    = GetEntryValue(0x0028, 0x0010);
146          std::string columns = GetEntryValue(0x0028, 0x0011);
147          SetValEntry(columns, 0x0028, 0x0010);
148          SetValEntry(rows   , 0x0028, 0x0011);
149    }
150    // --- End of ACR-LibIDO kludge --- 
151 }
152
153 /**
154  * \brief This default constructor doesn't parse the file. You should
155  *        then invoke \ref Document::SetFileName and then the parsing.
156  */
157 Document::Document() 
158          :ElementSet(-1)
159 {
160    Fp = 0;
161
162    SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
163    Initialize();
164    SwapCode = 1234;
165    Filetype = ExplicitVR;
166    Group0002Parsed = false;
167 }
168
169 /**
170  * \brief   Canonical destructor.
171  */
172 Document::~Document ()
173 {
174    RefPubDict = NULL;
175    RefShaDict = NULL;
176 }
177
178 //-----------------------------------------------------------------------------
179 // Public
180 /**
181  * \brief   Get the public dictionary used
182  */
183 Dict *Document::GetPubDict()
184 {
185    return RefPubDict;
186 }
187
188 /**
189  * \brief   Get the shadow dictionary used
190  */
191 Dict *Document::GetShaDict()
192 {
193    return RefShaDict;
194 }
195
196 /**
197  * \brief   Set the shadow dictionary used
198  * @param   dict dictionary to use in shadow
199  */
200 bool Document::SetShaDict(Dict *dict)
201 {
202    RefShaDict = dict;
203    return !RefShaDict;
204 }
205
206 /**
207  * \brief   Set the shadow dictionary used
208  * @param   dictName name of the dictionary to use in shadow
209  */
210 bool Document::SetShaDict(DictKey const &dictName)
211 {
212    RefShaDict = Global::GetDicts()->GetDict(dictName);
213    return !RefShaDict;
214 }
215
216 /**
217  * \brief  This predicate, based on hopefully reasonable heuristics,
218  *         decides whether or not the current Document was properly parsed
219  *         and contains the mandatory information for being considered as
220  *         a well formed and usable Dicom/Acr File.
221  * @return true when Document is the one of a reasonable Dicom/Acr file,
222  *         false otherwise. 
223  */
224 bool Document::IsReadable()
225 {
226    if( Filetype == Unknown)
227    {
228       gdcmVerboseMacro( "Wrong filetype");
229       return false;
230    }
231
232    if ( IsEmpty() )
233    { 
234       gdcmVerboseMacro( "No tag in internal hash table.");
235       return false;
236    }
237
238    return true;
239 }
240
241 /**
242  * \brief   Predicate for dicom version 3 file.
243  * @return  True when the file is a dicom version 3.
244  */
245 bool Document::IsDicomV3()
246 {
247    // Checking if Transfer Syntax exists is enough
248    // Anyway, it's to late check if the 'Preamble' was found ...
249    // And ... would it be a rich idea to check ?
250    // (some 'no Preamble' DICOM images exist !)
251    return GetDocEntry(0x0002, 0x0010) != NULL;
252 }
253
254 /**
255  * \brief   Predicate for Papyrus file
256  *          Dedicated to whomsoever it may concern
257  * @return  True when the file is a Papyrus file.
258  */
259 bool Document::IsPapyrus()
260 {
261    // check for Papyrus private Sequence
262    DocEntry *e = GetDocEntry(0x0041, 0x1050);
263    if ( !e )
264       return false;
265    // check if it's actually a Sequence
266    if ( !dynamic_cast<SeqEntry*>(e) )
267       return  false;
268    return true;
269 }
270
271 /**
272  * \brief  returns the File Type 
273  *         (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
274  * @return the FileType code
275  */
276 FileType Document::GetFileType()
277 {
278    return Filetype;
279 }
280
281 /**
282  * \brief   Accessor to the Transfer Syntax (when present) of the
283  *          current document (it internally handles reading the
284  *          value from disk when only parsing occured).
285  * @return  The encountered Transfer Syntax of the current document.
286  */
287 std::string Document::GetTransferSyntax()
288 {
289    DocEntry *entry = GetDocEntry(0x0002, 0x0010);
290    if ( !entry )
291    {
292       return GDCM_UNKNOWN;
293    }
294
295    // The entry might be present but not loaded (parsing and loading
296    // happen at different stages): try loading and proceed with check...
297    LoadDocEntrySafe(entry);
298    if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
299    {
300       std::string transfer = valEntry->GetValue();
301       // The actual transfer (as read from disk) might be padded. We
302       // first need to remove the potential padding. We can make the
303       // weak assumption that padding was not executed with digits...
304       if  ( transfer.length() == 0 )
305       {
306          // for brain damaged headers
307          return GDCM_UNKNOWN;
308       }
309       while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
310       {
311          transfer.erase(transfer.length()-1, 1);
312       }
313       return transfer;
314    }
315    return GDCM_UNKNOWN;
316 }
317
318 /**
319  * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
320  * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
321  */
322 std::string Document::GetTransferSyntaxName()
323 {
324    // use the TS (TS : Transfer Syntax)
325    std::string transferSyntax = GetEntryValue(0x0002,0x0010);
326
327    if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
328    {
329       gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
330                << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
331       return "Uncompressed ACR-NEMA";
332    }
333    if ( transferSyntax == GDCM_UNFOUND )
334    {
335       gdcmVerboseMacro( "Unfound Transfer Syntax (0002,0010)");
336       return "Uncompressed ACR-NEMA";
337    }
338
339    // we do it only when we need it
340    const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
341
342    // Global::GetTS() is a global static you shall never try to delete it!
343    return tsName;
344 }
345 //
346 // --------------- Swap Code ------------------
347 /**
348  * \brief   Swaps the bytes so they agree with the processor order
349  * @return  The properly swaped 16 bits integer.
350  */
351 uint16_t Document::SwapShort(uint16_t a)
352 {
353    if ( SwapCode == 4321 || SwapCode == 2143 )
354    {
355       a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
356    }
357    return a;
358 }
359
360 /**
361  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
362  *          processor order.
363  * @return  The properly swaped 32 bits integer.
364  */
365 uint32_t Document::SwapLong(uint32_t a)
366 {
367    switch (SwapCode)
368    {
369       case 1234 :
370          break;
371       case 4321 :
372          a=( ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000) | 
373              ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
374          break;   
375       case 3412 :
376          a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
377          break;  
378       case 2143 :
379          a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
380       break;
381       default :
382          gdcmErrorMacro( "Unset swap code:" << SwapCode );
383          a = 0;
384    }
385    return a;
386
387
388 //
389 // -----------------File I/O ---------------
390 /**
391  * \brief  Tries to open the file \ref Document::Filename and
392  *         checks the preamble when existing.
393  * @return The FILE pointer on success. 
394  */
395 std::ifstream *Document::OpenFile()
396 {
397    HasDCMPreamble = false;
398    if (Filename.length() == 0) 
399    {
400       return 0;
401    }
402
403    if(Fp)
404    {
405       gdcmVerboseMacro( "File already open: " << Filename.c_str());
406       CloseFile();
407    }
408
409    Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
410    if( ! *Fp )
411    {
412       gdcmDebugMacro( "Cannot open file: " << Filename.c_str());
413       delete Fp;
414       Fp = 0;
415       return 0;
416    }
417  
418    uint16_t zero;
419    Fp->read((char*)&zero, (size_t)2);
420    if( Fp->eof() )
421    {
422       CloseFile();
423       return 0;
424    }
425  
426    //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
427    if( 
428        zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
429        zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
430        zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
431        zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
432    {
433       std::string msg 
434          = Util::Format("ACR/DICOM with no preamble: (%04x)\n", zero);
435       gdcmVerboseMacro( msg.c_str() );
436       return Fp;
437    }
438  
439    //DICOM
440    Fp->seekg(126L, std::ios::cur);
441    char dicm[4];
442    Fp->read(dicm,  (size_t)4);
443    if( Fp->eof() )
444    {
445       CloseFile();
446       return 0;
447    }
448    if( memcmp(dicm, "DICM", 4) == 0 )
449    {
450       HasDCMPreamble = true;
451       return Fp;
452    }
453  
454    CloseFile();
455    gdcmVerboseMacro( "Not DICOM/ACR (missing preamble)" << Filename.c_str());
456  
457    return 0;
458 }
459
460 /**
461  * \brief closes the file  
462  * @return  TRUE if the close was successfull 
463  */
464 bool Document::CloseFile()
465 {
466    if( Fp )
467    {
468       Fp->close();
469       delete Fp;
470       Fp = 0;
471    }
472    return true; //FIXME how do we detect a non-closed ifstream ?
473 }
474
475 /**
476  * \brief Writes in a file all the Header Entries (Dicom Elements) 
477  * @param fp file pointer on an already open file (actually: Output File Stream)
478  * @param filetype Type of the File to be written 
479  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
480  * @return Always true.
481  */
482 void Document::WriteContent(std::ofstream *fp, FileType filetype)
483 {
484    // \TODO move the following lines (and a lot of others, to be written)
485    // to a future function CheckAndCorrectHeader  
486
487    // (necessary if user wants to write a DICOM V3 file
488    // starting from an ACR-NEMA (V2) Header
489
490    if ( filetype == ImplicitVR || filetype == ExplicitVR )
491    {
492       // writing Dicom File Preamble
493       char filePreamble[128];
494       memset(filePreamble, 0, 128);
495       fp->write(filePreamble, 128);
496       fp->write("DICM", 4);
497    }
498
499 /*
500  * \todo rewrite later, if really usefull
501  *       - 'Group Length' element is optional in DICOM
502  *       - but un-updated odd groups lengthes can causes pb
503  *         (xmedcon breaker)
504  *
505  * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
506  *    UpdateGroupLength(false,filetype);
507  * if ( filetype == ACR)
508  *    UpdateGroupLength(true,ACR);
509  */
510  
511    ElementSet::WriteContent(fp, filetype); // This one is recursive
512 }
513
514 // -----------------------------------------
515 // Content entries 
516 /**
517  * \brief Loads (from disk) the element content 
518  *        when a string is not suitable
519  * @param group   group number of the Entry 
520  * @param elem  element number of the Entry
521  */
522 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
523 {
524    // Search the corresponding DocEntry
525    DocEntry *docElement = GetDocEntry(group, elem);
526    if ( !docElement )
527       return;
528
529    BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
530    if( !binElement )
531       return;
532
533    LoadEntryBinArea(binElement);
534 }
535
536 /**
537  * \brief Loads (from disk) the element content 
538  *        when a string is not suitable
539  * @param elem  Entry whose binArea is going to be loaded
540  */
541 void Document::LoadEntryBinArea(BinEntry *elem) 
542 {
543    if(elem->GetBinArea())
544       return;
545
546    bool openFile = !Fp;
547    if(openFile)
548       OpenFile();
549
550    size_t o =(size_t)elem->GetOffset();
551    Fp->seekg(o, std::ios::beg);
552
553    size_t l = elem->GetLength();
554    uint8_t *a = new uint8_t[l];
555    if( !a )
556    {
557       gdcmVerboseMacro( "Cannot allocate BinEntry content");
558       return;
559    }
560
561    /// \todo check the result 
562    Fp->read((char*)a, l);
563    if( Fp->fail() || Fp->eof())
564    {
565       delete[] a;
566       return;
567    }
568
569    elem->SetBinArea(a);
570
571    if(openFile)
572       CloseFile();
573 }
574
575 /**
576  * \brief  Loads the element while preserving the current
577  *         underlying file position indicator as opposed to
578  *        LoadDocEntry that modifies it.
579  * @param entry   Header Entry whose value will be loaded. 
580  * @return  
581  */
582 void Document::LoadDocEntrySafe(DocEntry *entry)
583 {
584    if(Fp)
585    {
586       long PositionOnEntry = Fp->tellg();
587       LoadDocEntry(entry);
588       Fp->seekg(PositionOnEntry, std::ios::beg);
589    }
590 }
591
592 //-----------------------------------------------------------------------------
593 // Protected
594 /**
595  * \brief Reads a supposed to be 16 Bits integer
596  *       (swaps it depending on processor endianity) 
597  * @return read value
598  */
599 uint16_t Document::ReadInt16()
600    throw( FormatError )
601 {
602    uint16_t g;
603    Fp->read ((char*)&g, (size_t)2);
604    if ( Fp->fail() )
605    {
606       throw FormatError( "Document::ReadInt16()", " file error." );
607    }
608    if( Fp->eof() )
609    {
610       throw FormatError( "Document::ReadInt16()", "EOF." );
611    }
612    g = SwapShort(g); 
613    return g;
614 }
615
616 /**
617  * \brief  Reads a supposed to be 32 Bits integer
618  *         (swaps it depending on processor endianity)  
619  * @return read value
620  */
621 uint32_t Document::ReadInt32()
622    throw( FormatError )
623 {
624    uint32_t g;
625    Fp->read ((char*)&g, (size_t)4);
626    if ( Fp->fail() )
627    {
628       throw FormatError( "Document::ReadInt32()", " file error." );
629    }
630    if( Fp->eof() )
631    {
632       throw FormatError( "Document::ReadInt32()", "EOF." );
633    }
634    g = SwapLong(g);
635    return g;
636 }
637
638 /**
639  * \brief skips bytes inside the source file 
640  * \warning NOT end user intended method !
641  * @return 
642  */
643 void Document::SkipBytes(uint32_t nBytes)
644 {
645    //FIXME don't dump the returned value
646    Fp->seekg((long)nBytes, std::ios::cur);
647 }
648
649 /**
650  * \brief   Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
651  * @param filetype Type of the File to be written 
652  */
653 int Document::ComputeGroup0002Length( FileType filetype ) 
654 {
655    uint16_t gr;
656    std::string vr;
657    
658    int groupLength = 0;
659    bool found0002 = false;   
660   
661    // for each zero-level Tag in the DCM Header
662    DocEntry *entry = GetFirstEntry();
663    while( entry )
664    {
665       gr = entry->GetGroup();
666
667       if( gr == 0x0002 )
668       {
669          found0002 = true;
670
671          if( entry->GetElement() != 0x0000 )
672          {
673             vr = entry->GetVR();
674  
675             if( filetype == ExplicitVR )
676             {
677                if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ) 
678                {
679                   // explicit VR AND OB, OW, SQ : 4 more bytes
680                   groupLength +=  4;
681                }
682             }
683             groupLength += 2 + 2 + 4 + entry->GetLength();   
684          }
685       }
686       else if (found0002 )
687          break;
688
689       entry = GetNextEntry();
690    }
691    return groupLength; 
692 }
693
694 //-----------------------------------------------------------------------------
695 // Private
696 /**
697  * \brief   Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
698  * @return  length of the parsed set. 
699  */ 
700 void Document::ParseDES(DocEntrySet *set, long offset, 
701                         long l_max, bool delim_mode)
702 {
703    DocEntry *newDocEntry = 0;
704    ValEntry *newValEntry;
705    BinEntry *newBinEntry;
706    SeqEntry *newSeqEntry;
707    VRKey vr;
708    bool used = false;
709
710    while (true)
711    {
712       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
713       {
714          break;
715       }
716
717       used = true;
718       newDocEntry = ReadNextDocEntry( );
719
720       if ( !newDocEntry )
721       {
722          break;
723       }
724
725       vr = newDocEntry->GetVR();
726       newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
727       newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
728       newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
729
730       if ( newValEntry || newBinEntry )
731       {
732          if ( newBinEntry )
733          {
734             if ( Filetype == ExplicitVR && 
735                  !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
736             { 
737                 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
738                 gdcmVerboseMacro( std::hex << newDocEntry->GetGroup() 
739                                   << "|" << newDocEntry->GetElement()
740                                   << " : Neither Valentry, nor BinEntry." 
741                                   "Probably unknown VR.");
742             }
743
744          //////////////////// BinEntry or UNKOWN VR:
745             // When "this" is a Document the Key is simply of the
746             // form ( group, elem )...
747             if ( dynamic_cast< Document* > ( set ) )
748             {
749                newBinEntry->SetKey( newBinEntry->GetKey() );
750             }
751             // but when "this" is a SQItem, we are inserting this new
752             // valEntry in a sequence item, and the key has the
753             // generalized form (refer to \ref BaseTagKey):
754             if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
755             {
756                newBinEntry->SetKey(  parentSQItem->GetBaseTagKey()
757                                    + newBinEntry->GetKey() );
758             }
759
760             LoadDocEntry( newBinEntry );
761             if( !set->AddEntry( newBinEntry ) )
762             {
763               //Expect big troubles if here
764               //delete newBinEntry;
765               used=false;
766             }
767          }
768          else
769          {
770          /////////////////////// ValEntry
771             // When "set" is a Document, then we are at the top of the
772             // hierarchy and the Key is simply of the form ( group, elem )...
773             if ( dynamic_cast< Document* > ( set ) )
774             {
775                newValEntry->SetKey( newValEntry->GetKey() );
776             }
777             // ...but when "set" is a SQItem, we are inserting this new
778             // valEntry in a sequence item. Hence the key has the
779             // generalized form (refer to \ref BaseTagKey):
780             if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
781             {
782                newValEntry->SetKey(  parentSQItem->GetBaseTagKey()
783                                    + newValEntry->GetKey() );
784             }
785              
786             LoadDocEntry( newValEntry );
787             bool delimitor=newValEntry->IsItemDelimitor();
788             if( !set->AddEntry( newValEntry ) )
789             {
790               // If here expect big troubles
791               //delete newValEntry; //otherwise mem leak
792               used=false;
793             }
794
795             if (delimitor)
796             {
797                if(!used)
798                   delete newDocEntry;
799                break;
800             }
801             if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
802             {
803                if(!used)
804                   delete newDocEntry;
805                break;
806             }
807          }
808
809          // Just to make sure we are at the beginning of next entry.
810          SkipToNextDocEntry(newDocEntry);
811       }
812       else
813       {
814          // VR = "SQ"
815          unsigned long l = newDocEntry->GetReadLength();            
816          if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
817          {
818             if ( l == 0xffffffff )
819             {
820               delim_mode = true;
821             }
822             else
823             {
824               delim_mode = false;
825             }
826          }
827          // no other way to create it ...
828          newSeqEntry->SetDelimitorMode( delim_mode );
829
830          // At the top of the hierarchy, stands a Document. When "set"
831          // is a Document, then we are building the first depth level.
832          // Hence the SeqEntry we are building simply has a depth
833          // level of one:
834          if (/*Document *dummy =*/ dynamic_cast< Document* > ( set ) )
835          {
836             //(void)dummy;
837             newSeqEntry->SetDepthLevel( 1 );
838             newSeqEntry->SetKey( newSeqEntry->GetKey() );
839          }
840          // But when "set" is already a SQItem, we are building a nested
841          // sequence, and hence the depth level of the new SeqEntry
842          // we are building, is one level deeper:
843          if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
844          {
845             newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
846             newSeqEntry->SetKey(  parentSQItem->GetBaseTagKey()
847                                 + newSeqEntry->GetKey() );
848          }
849
850          if ( l != 0 )
851          {  // Don't try to parse zero-length sequences
852             ParseSQ( newSeqEntry, 
853                      newDocEntry->GetOffset(),
854                      l, delim_mode);
855          }
856          if( !set->AddEntry( newSeqEntry ) )
857          {
858             used = false;
859          }
860          if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
861          {
862             if( !used )
863                delete newDocEntry;
864             break;
865          }
866       }
867
868       if( !used )
869          delete newDocEntry;
870    }
871 }
872
873 /**
874  * \brief   Parses a Sequence ( SeqEntry after SeqEntry)
875  * @return  parsed length for this level
876  */ 
877 void Document::ParseSQ( SeqEntry *seqEntry,
878                         long offset, long l_max, bool delim_mode)
879 {
880    int SQItemNumber = 0;
881    bool dlm_mod;
882    long offsetStartCurrentSQItem = offset;
883
884    while (true)
885    {
886       // the first time, we read the fff0,e000 of the first SQItem
887       DocEntry *newDocEntry = ReadNextDocEntry();
888
889       if ( !newDocEntry )
890       {
891          // FIXME Should warn user
892          break;
893       }
894       if( delim_mode )
895       {
896          if ( newDocEntry->IsSequenceDelimitor() )
897          {
898             seqEntry->SetDelimitationItem( newDocEntry ); 
899             break;
900          }
901       }
902       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
903       {
904          delete newDocEntry;
905          break;
906       }
907       // create the current SQItem
908       SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
909       std::ostringstream newBase;
910       newBase << seqEntry->GetKey()
911               << "/"
912               << SQItemNumber
913               << "#";
914       itemSQ->SetBaseTagKey( newBase.str() );
915       unsigned int l = newDocEntry->GetReadLength();
916       
917       if ( l == 0xffffffff )
918       {
919          dlm_mod = true;
920       }
921       else
922       {
923          dlm_mod = false;
924       }
925       // FIXME, TODO
926       // when we're here, element fffe,e000 is already passed.
927       // it's lost for the SQItem we're going to process !!
928
929       //ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
930       //delete newDocEntry; // FIXME well ... it's too late to use it !
931
932       // Let's try :------------
933       // remove fff0,e000, created out of the SQItem
934       delete newDocEntry;
935       Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
936       // fill up the current SQItem, starting at the beginning of fff0,e000
937       ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
938       offsetStartCurrentSQItem = Fp->tellg();
939       // end try -----------------
940  
941       seqEntry->AddSQItem( itemSQ, SQItemNumber ); 
942       SQItemNumber++;
943       if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
944       {
945          break;
946       }
947    }
948 }
949
950 /**
951  * \brief   Loads the element content if its length doesn't exceed
952  *          the value specified with Document::SetMaxSizeLoadEntry()
953  * @param   entry Header Entry (Dicom Element) to be dealt with
954  */
955 void Document::LoadDocEntry(DocEntry *entry)
956 {
957    uint16_t group  = entry->GetGroup();
958    std::string  vr = entry->GetVR();
959    uint32_t length = entry->GetLength();
960
961    Fp->seekg((long)entry->GetOffset(), std::ios::beg);
962
963    // A SeQuence "contains" a set of Elements.  
964    //          (fffe e000) tells us an Element is beginning
965    //          (fffe e00d) tells us an Element just ended
966    //          (fffe e0dd) tells us the current SeQuence just ended
967    if( group == 0xfffe )
968    {
969       // NO more value field for SQ !
970       return;
971    }
972
973    // When the length is zero things are easy:
974    if ( length == 0 )
975    {
976       ((ValEntry *)entry)->SetValue("");
977       return;
978    }
979
980    // The elements whose length is bigger than the specified upper bound
981    // are not loaded. Instead we leave a short notice of the offset of
982    // the element content and it's length.
983
984    std::ostringstream s;
985    if (length > MaxSizeLoadEntry)
986    {
987       if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
988       {  
989          //s << "gdcm::NotLoaded (BinEntry)";
990          s << GDCM_NOTLOADED;
991          s << " Address:" << (long)entry->GetOffset();
992          s << " Length:"  << entry->GetLength();
993          s << " x(" << std::hex << entry->GetLength() << ")";
994          binEntryPtr->SetValue(s.str());
995       }
996       // Be carefull : a BinEntry IS_A ValEntry ... 
997       else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
998       {
999         // s << "gdcm::NotLoaded. (ValEntry)";
1000          s << GDCM_NOTLOADED;  
1001          s << " Address:" << (long)entry->GetOffset();
1002          s << " Length:"  << entry->GetLength();
1003          s << " x(" << std::hex << entry->GetLength() << ")";
1004          valEntryPtr->SetValue(s.str());
1005       }
1006       else
1007       {
1008          // fusible
1009          gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1010                       << "nor a ValEntry ?! Should never print that !" );
1011       }
1012
1013       // to be sure we are at the end of the value ...
1014       Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1015                 std::ios::beg);
1016       return;
1017    }
1018
1019    // When we find a BinEntry not very much can be done :
1020    if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1021    {
1022       s << GDCM_BINLOADED;
1023       binEntryPtr->SetValue(s.str());
1024       LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1025       return;
1026    }
1027
1028    /// \todo Any compacter code suggested (?)
1029    if ( IsDocEntryAnInteger(entry) )
1030    {   
1031       uint32_t NewInt;
1032       int nbInt;
1033       // When short integer(s) are expected, read and convert the following 
1034       // n *two characters properly i.e. consider them as short integers as
1035       // opposed to strings.
1036       // Elements with Value Multiplicity > 1
1037       // contain a set of integers (not a single one)       
1038       if (vr == "US" || vr == "SS")
1039       {
1040          nbInt = length / 2;
1041          NewInt = ReadInt16();
1042          s << NewInt;
1043          if (nbInt > 1)
1044          {
1045             for (int i=1; i < nbInt; i++)
1046             {
1047                s << '\\';
1048                NewInt = ReadInt16();
1049                s << NewInt;
1050             }
1051          }
1052       }
1053       // See above comment on multiple integers (mutatis mutandis).
1054       else if (vr == "UL" || vr == "SL")
1055       {
1056          nbInt = length / 4;
1057          NewInt = ReadInt32();
1058          s << NewInt;
1059          if (nbInt > 1)
1060          {
1061             for (int i=1; i < nbInt; i++)
1062             {
1063                s << '\\';
1064                NewInt = ReadInt32();
1065                s << NewInt;
1066             }
1067          }
1068       }
1069 #ifdef GDCM_NO_ANSI_STRING_STREAM
1070       s << std::ends; // to avoid oddities on Solaris
1071 #endif //GDCM_NO_ANSI_STRING_STREAM
1072
1073       ((ValEntry *)entry)->SetValue(s.str());
1074       return;
1075    }
1076    
1077   // FIXME: We need an additional byte for storing \0 that is not on disk
1078    char *str = new char[length+1];
1079    Fp->read(str, (size_t)length);
1080    str[length] = '\0'; //this is only useful when length is odd
1081    // Special DicomString call to properly handle \0 and even length
1082    std::string newValue;
1083    if( length % 2 )
1084    {
1085       newValue = Util::DicomString(str, length+1);
1086       gdcmVerboseMacro("Warning: bad length: " << length <<
1087                        ",For string :" <<  newValue.c_str()); 
1088       // Since we change the length of string update it length
1089       //entry->SetReadLength(length+1);
1090    }
1091    else
1092    {
1093       newValue = Util::DicomString(str, length);
1094    }
1095    delete[] str;
1096
1097    if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1098    {
1099       if ( Fp->fail() || Fp->eof())
1100       {
1101          gdcmVerboseMacro("Unread element value");
1102          valEntry->SetValue(GDCM_UNREAD);
1103          return;
1104       }
1105
1106       if( vr == "UI" )
1107       {
1108          // Because of correspondance with the VR dic
1109          valEntry->SetValue(newValue);
1110       }
1111       else
1112       {
1113          valEntry->SetValue(newValue);
1114       }
1115    }
1116    else
1117    {
1118       gdcmErrorMacro( "Should have a ValEntry, here !");
1119    }
1120 }
1121
1122 /**
1123  * \brief  Find the value Length of the passed Header Entry
1124  * @param  entry Header Entry whose length of the value shall be loaded. 
1125  */
1126 void Document::FindDocEntryLength( DocEntry *entry )
1127    throw ( FormatError )
1128 {
1129    std::string  vr  = entry->GetVR();
1130    uint16_t length16;       
1131    
1132    if ( Filetype == ExplicitVR && !entry->IsImplicitVR() ) 
1133    {
1134       if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" ) 
1135       {
1136          // The following reserved two bytes (see PS 3.5-2003, section
1137          // "7.1.2 Data element structure with explicit vr", p 27) must be
1138          // skipped before proceeding on reading the length on 4 bytes.
1139          Fp->seekg( 2L, std::ios::cur);
1140          uint32_t length32 = ReadInt32();
1141
1142          if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff ) 
1143          {
1144             uint32_t lengthOB;
1145             try 
1146             {
1147                lengthOB = FindDocEntryLengthOBOrOW();
1148             }
1149             catch ( FormatUnexpected )
1150             {
1151                // Computing the length failed (this happens with broken
1152                // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1153                // chance to get the pixels by deciding the element goes
1154                // until the end of the file. Hence we artificially fix the
1155                // the length and proceed.
1156                long currentPosition = Fp->tellg();
1157                Fp->seekg(0L,std::ios::end);
1158
1159                long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1160                Fp->seekg(currentPosition, std::ios::beg);
1161
1162                entry->SetReadLength(lengthUntilEOF);
1163                entry->SetLength(lengthUntilEOF);
1164                return;
1165             }
1166             entry->SetReadLength(lengthOB);
1167             entry->SetLength(lengthOB);
1168             return;
1169          }
1170          FixDocEntryFoundLength(entry, length32); 
1171          return;
1172       }
1173
1174       // Length is encoded on 2 bytes.
1175       length16 = ReadInt16();
1176
1177       // FIXME : This heuristic supposes that the first group following
1178       //         group 0002 *has* and element 0000.
1179       // BUT ... Element 0000 is optionnal :-(
1180
1181
1182    // Fixed using : HandleOutOfGroup0002()
1183    //              (first hereafter strategy ...)
1184       
1185       // We can tell the current file is encoded in big endian (like
1186       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1187       // and it's value is the one of the encoding of a big endian file.
1188       // In order to deal with such big endian encoded files, we have
1189       // (at least) two strategies:
1190       // * when we load the "Transfer Syntax" tag with value of big endian
1191       //   encoding, we raise the proper flags. Then we wait for the end
1192       //   of the META group (0x0002) among which is "Transfer Syntax",
1193       //   before switching the swap code to big endian. We have to postpone
1194       //   the switching of the swap code since the META group is fully encoded
1195       //   in little endian, and big endian coding only starts at the next
1196       //   group. The corresponding code can be hard to analyse and adds
1197       //   many additional unnecessary tests for regular tags.
1198       // * the second strategy consists in waiting for trouble, that shall
1199       //   appear when we find the first group with big endian encoding. This
1200       //   is easy to detect since the length of a "Group Length" tag (the
1201       //   ones with zero as element number) has to be of 4 (0x0004). When we
1202       //   encounter 1024 (0x0400) chances are the encoding changed and we
1203       //   found a group with big endian encoding.
1204       //---> Unfortunately, element 0000 is optional.
1205       //---> This will not work when missing!
1206       // We shall use this second strategy. In order to make sure that we
1207       // can interpret the presence of an apparently big endian encoded
1208       // length of a "Group Length" without committing a big mistake, we
1209       // add an additional check: we look in the already parsed elements
1210       // for the presence of a "Transfer Syntax" whose value has to be "big
1211       // endian encoding". When this is the case, chances are we have got our
1212       // hands on a big endian encoded file: we switch the swap code to
1213       // big endian and proceed...
1214
1215 //      if ( element  == 0x0000 && length16 == 0x0400 ) 
1216 //      {
1217 //         std::string ts = GetTransferSyntax();
1218 //         if ( Global::GetTS()->GetSpecialTransferSyntax(ts) 
1219 //                != TS::ExplicitVRBigEndian ) 
1220 //         {
1221 //            throw FormatError( "Document::FindDocEntryLength()",
1222 //                               " not explicit VR." );
1223 //           return;
1224 //        }
1225 //        length16 = 4;
1226 //        SwitchByteSwapCode();
1227 //
1228 //         // Restore the unproperly loaded values i.e. the group, the element
1229 //         // and the dictionary entry depending on them.
1230 //         uint16_t correctGroup = SwapShort( entry->GetGroup() );
1231 //         uint16_t correctElem  = SwapShort( entry->GetElement() );
1232 //         DictEntry *newTag = GetDictEntry( correctGroup, correctElem );
1233 //         if ( !newTag )
1234 //         {
1235 //            // This correct tag is not in the dictionary. Create a new one.
1236 //            newTag = NewVirtualDictEntry(correctGroup, correctElem);
1237 //         }
1238 //         // FIXME this can create a memory leaks on the old entry that be
1239 //         // left unreferenced.
1240 //         entry->SetDictEntry( newTag );
1241 //      }
1242   
1243       // 0xffff means that we deal with 'No Length' Sequence 
1244       //        or 'No Length' SQItem
1245       if ( length16 == 0xffff) 
1246       {           
1247          length16 = 0;
1248       }
1249       FixDocEntryFoundLength( entry, (uint32_t)length16 );
1250       return;
1251    }
1252    else
1253    {
1254       // Either implicit VR or a non DICOM conformal (see note below) explicit
1255       // VR that ommited the VR of (at least) this element. Farts happen.
1256       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1257       // on Data elements "Implicit and Explicit VR Data Elements shall
1258       // not coexist in a Data Set and Data Sets nested within it".]
1259       // Length is on 4 bytes.
1260
1261      // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1262      // even if Transfer Syntax is 'Implicit VR ...' 
1263       
1264       FixDocEntryFoundLength( entry, ReadInt32() );
1265       return;
1266    }
1267 }
1268
1269 /**
1270  * \brief  Find the Length till the next sequence delimiter
1271  * \warning NOT end user intended method !
1272  * @return 
1273  */
1274 uint32_t Document::FindDocEntryLengthOBOrOW()
1275    throw( FormatUnexpected )
1276 {
1277    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1278    long positionOnEntry = Fp->tellg();
1279    bool foundSequenceDelimiter = false;
1280    uint32_t totalLength = 0;
1281
1282    while ( !foundSequenceDelimiter )
1283    {
1284       uint16_t group;
1285       uint16_t elem;
1286       try
1287       {
1288          group = ReadInt16();
1289          elem  = ReadInt16();   
1290       }
1291       catch ( FormatError )
1292       {
1293          throw FormatError("Unexpected end of file encountered during ",
1294                            "Document::FindDocEntryLengthOBOrOW()");
1295       }
1296       // We have to decount the group and element we just read
1297       totalLength += 4;     
1298       if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1299       {
1300          long filePosition = Fp->tellg();
1301          gdcmVerboseMacro( "Neither an Item tag nor a Sequence delimiter tag on :" 
1302            << std::hex << group << " , " << elem 
1303            << ") -before- position x(" << filePosition << ")" );
1304   
1305          Fp->seekg(positionOnEntry, std::ios::beg);
1306          throw FormatUnexpected( "Neither an Item tag nor a Sequence delimiter tag.");
1307       }
1308       if ( elem == 0xe0dd )
1309       {
1310          foundSequenceDelimiter = true;
1311       }
1312       uint32_t itemLength = ReadInt32();
1313       // We add 4 bytes since we just read the ItemLength with ReadInt32
1314       totalLength += itemLength + 4;
1315       SkipBytes(itemLength);
1316       
1317       if ( foundSequenceDelimiter )
1318       {
1319          break;
1320       }
1321    }
1322    Fp->seekg( positionOnEntry, std::ios::beg);
1323    return totalLength;
1324 }
1325
1326 /**
1327  * \brief     Find the Value Representation of the current Dicom Element.
1328  * @return    Value Representation of the current Entry
1329  */
1330 std::string Document::FindDocEntryVR()
1331 {
1332    if ( Filetype != ExplicitVR )
1333       return GDCM_UNKNOWN;
1334
1335    long positionOnEntry = Fp->tellg();
1336    // Warning: we believe this is explicit VR (Value Representation) because
1337    // we used a heuristic that found "UL" in the first tag. Alas this
1338    // doesn't guarantee that all the tags will be in explicit VR. In some
1339    // cases (see e-film filtered files) one finds implicit VR tags mixed
1340    // within an explicit VR file. Hence we make sure the present tag
1341    // is in explicit VR and try to fix things if it happens not to be
1342    // the case.
1343
1344    char vr[3];
1345    Fp->read (vr, (size_t)2);
1346    vr[2] = 0;
1347
1348    if( !CheckDocEntryVR(vr) )
1349    {
1350       Fp->seekg(positionOnEntry, std::ios::beg);
1351       return GDCM_UNKNOWN;
1352    }
1353    return vr;
1354 }
1355
1356 /**
1357  * \brief     Check the correspondance between the VR of the header entry
1358  *            and the taken VR. If they are different, the header entry is 
1359  *            updated with the new VR.
1360  * @param     vr    Dicom Value Representation
1361  * @return    false if the VR is incorrect of if the VR isn't referenced
1362  *            otherwise, it returns true
1363 */
1364 bool Document::CheckDocEntryVR(VRKey vr)
1365 {
1366    // CLEANME searching the dicom_vr at each occurence is expensive.
1367    // PostPone this test in an optional integrity check at the end
1368    // of parsing or only in debug mode.
1369    if ( !Global::GetVR()->IsValidVR(vr) )
1370       return false;
1371
1372    return true; 
1373 }
1374
1375 /**
1376  * \brief   Get the transformed value of the header entry. The VR value 
1377  *          is used to define the transformation to operate on the value
1378  * \warning NOT end user intended method !
1379  * @param   entry entry to tranform
1380  * @return  Transformed entry value
1381  */
1382 std::string Document::GetDocEntryValue(DocEntry *entry)
1383 {
1384    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1385    {
1386       std::string val = ((ValEntry *)entry)->GetValue();
1387       std::string vr  = entry->GetVR();
1388       uint32_t length = entry->GetLength();
1389       std::ostringstream s;
1390       int nbInt;
1391
1392       // When short integer(s) are expected, read and convert the following 
1393       // n * 2 bytes properly i.e. as a multivaluated strings
1394       // (each single value is separated fromthe next one by '\'
1395       // as usual for standard multivaluated filels
1396       // Elements with Value Multiplicity > 1
1397       // contain a set of short integers (not a single one) 
1398    
1399       if( vr == "US" || vr == "SS" )
1400       {
1401          uint16_t newInt16;
1402
1403          nbInt = length / 2;
1404          for (int i=0; i < nbInt; i++) 
1405          {
1406             if( i != 0 )
1407             {
1408                s << '\\';
1409             }
1410             newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1411             newInt16 = SwapShort( newInt16 );
1412             s << newInt16;
1413          }
1414       }
1415
1416       // When integer(s) are expected, read and convert the following 
1417       // n * 4 bytes properly i.e. as a multivaluated strings
1418       // (each single value is separated fromthe next one by '\'
1419       // as usual for standard multivaluated filels
1420       // Elements with Value Multiplicity > 1
1421       // contain a set of integers (not a single one) 
1422       else if( vr == "UL" || vr == "SL" )
1423       {
1424          uint32_t newInt32;
1425
1426          nbInt = length / 4;
1427          for (int i=0; i < nbInt; i++) 
1428          {
1429             if( i != 0)
1430             {
1431                s << '\\';
1432             }
1433             newInt32 = ( val[4*i+0] & 0xFF )
1434                     + (( val[4*i+1] & 0xFF ) <<  8 )
1435                     + (( val[4*i+2] & 0xFF ) << 16 )
1436                     + (( val[4*i+3] & 0xFF ) << 24 );
1437             newInt32 = SwapLong( newInt32 );
1438             s << newInt32;
1439          }
1440       }
1441 #ifdef GDCM_NO_ANSI_STRING_STREAM
1442       s << std::ends; // to avoid oddities on Solaris
1443 #endif //GDCM_NO_ANSI_STRING_STREAM
1444       return s.str();
1445    }
1446    return ((ValEntry *)entry)->GetValue();
1447 }
1448
1449 /**
1450  * \brief   Get the reverse transformed value of the header entry. The VR 
1451  *          value is used to define the reverse transformation to operate on
1452  *          the value
1453  * \warning NOT end user intended method !
1454  * @param   entry Entry to reverse transform
1455  * @return  Reverse transformed entry value
1456  */
1457 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1458 {
1459    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1460    {
1461       std::string vr = entry->GetVR();
1462       std::vector<std::string> tokens;
1463       std::ostringstream s;
1464
1465       if ( vr == "US" || vr == "SS" ) 
1466       {
1467          uint16_t newInt16;
1468
1469          tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1470          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1471          for (unsigned int i=0; i<tokens.size(); i++) 
1472          {
1473             newInt16 = atoi(tokens[i].c_str());
1474             s << (  newInt16        & 0xFF ) 
1475               << (( newInt16 >> 8 ) & 0xFF );
1476          }
1477          tokens.clear();
1478       }
1479       if ( vr == "UL" || vr == "SL")
1480       {
1481          uint32_t newInt32;
1482
1483          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1484          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1485          for (unsigned int i=0; i<tokens.size();i++) 
1486          {
1487             newInt32 = atoi(tokens[i].c_str());
1488             s << (char)(  newInt32         & 0xFF ) 
1489               << (char)(( newInt32 >>  8 ) & 0xFF )
1490               << (char)(( newInt32 >> 16 ) & 0xFF )
1491               << (char)(( newInt32 >> 24 ) & 0xFF );
1492          }
1493          tokens.clear();
1494       }
1495
1496 #ifdef GDCM_NO_ANSI_STRING_STREAM
1497       s << std::ends; // to avoid oddities on Solaris
1498 #endif //GDCM_NO_ANSI_STRING_STREAM
1499       return s.str();
1500    }
1501
1502    return ((ValEntry *)entry)->GetValue();
1503 }
1504
1505 /**
1506  * \brief   Skip a given Header Entry 
1507  * \warning NOT end user intended method !
1508  * @param   entry entry to skip
1509  */
1510 void Document::SkipDocEntry(DocEntry *entry) 
1511 {
1512    SkipBytes(entry->GetLength());
1513 }
1514
1515 /**
1516  * \brief   Skips to the beginning of the next Header Entry 
1517  * \warning NOT end user intended method !
1518  * @param   currentDocEntry entry to skip
1519  */
1520 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry) 
1521 {
1522    Fp->seekg((long)(currentDocEntry->GetOffset()),     std::ios::beg);
1523    if (currentDocEntry->GetGroup() != 0xfffe)  // for fffe pb
1524       Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1525 }
1526
1527 /**
1528  * \brief   When the length of an element value is obviously wrong (because
1529  *          the parser went Jabberwocky) one can hope improving things by
1530  *          applying some heuristics.
1531  * @param   entry entry to check
1532  * @param   foundLength first assumption about length    
1533  */
1534 void Document::FixDocEntryFoundLength(DocEntry *entry,
1535                                       uint32_t foundLength)
1536 {
1537    entry->SetReadLength( foundLength ); // will be updated only if a bug is found        
1538    if ( foundLength == 0xffffffff)
1539    {
1540       foundLength = 0;
1541    }
1542    
1543    uint16_t gr   = entry->GetGroup();
1544    uint16_t elem = entry->GetElement(); 
1545      
1546    if ( foundLength % 2)
1547    {
1548       gdcmVerboseMacro( "Warning : Tag with uneven length " << foundLength 
1549         <<  " in x(" << std::hex << gr << "," << elem <<")");
1550    }
1551       
1552    //////// Fix for some naughty General Electric images.
1553    // Allthough not recent many such GE corrupted images are still present
1554    // on Creatis hard disks. Hence this fix shall remain when such images
1555    // are no longer in use (we are talking a few years, here)...
1556    // Note: XMedCom probably uses such a trick since it is able to read
1557    //       those pesky GE images ...
1558    if ( foundLength == 13)
1559    {
1560       // Only happens for this length !
1561       if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1562       {
1563          foundLength = 10;
1564          entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1565       }
1566    }
1567
1568    //////// Fix for some brain-dead 'Leonardo' Siemens images.
1569    // Occurence of such images is quite low (unless one leaves close to a
1570    // 'Leonardo' source. Hence, one might consider commenting out the
1571    // following fix on efficiency reasons.
1572    else if ( gr   == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1573    {
1574       foundLength = 4;
1575       entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1576    } 
1577  
1578    else if ( entry->GetVR() == "SQ" )
1579    {
1580       foundLength = 0;      // ReadLength is unchanged 
1581    } 
1582     
1583    //////// We encountered a 'delimiter' element i.e. a tag of the form 
1584    // "fffe|xxxx" which is just a marker. Delimiters length should not be
1585    // taken into account.
1586    else if( gr == 0xfffe )
1587    {    
1588      // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1589      // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1590      // causes extra troubles...
1591      if( entry->GetElement() != 0x0000 )
1592      {
1593         foundLength = 0;
1594      }
1595    }            
1596    entry->SetLength(foundLength);
1597 }
1598
1599 /**
1600  * \brief   Apply some heuristics to predict whether the considered 
1601  *          element value contains/represents an integer or not.
1602  * @param   entry The element value on which to apply the predicate.
1603  * @return  The result of the heuristical predicate.
1604  */
1605 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1606 {
1607    uint16_t elem          = entry->GetElement();
1608    uint16_t group         = entry->GetGroup();
1609    const std::string &vr  = entry->GetVR();
1610    uint32_t length        = entry->GetLength();
1611
1612    // When we have some semantics on the element we just read, and if we
1613    // a priori know we are dealing with an integer, then we shall be
1614    // able to swap it's element value properly.
1615    if ( elem == 0 )  // This is the group length of the group
1616    {  
1617       if ( length == 4 )
1618       {
1619          return true;
1620       }
1621       else 
1622       {
1623          // Allthough this should never happen, still some images have a
1624          // corrupted group length [e.g. have a glance at offset x(8336) of
1625          // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1626          // Since for dicom compliant and well behaved headers, the present
1627          // test is useless (and might even look a bit paranoid), when we
1628          // encounter such an ill-formed image, we simply display a warning
1629          // message and proceed on parsing (while crossing fingers).
1630          long filePosition = Fp->tellg();
1631          gdcmVerboseMacro( "Erroneous Group Length element length  on : (" 
1632            << std::hex << group << " , " << elem
1633            << ") -before- position x(" << filePosition << ")"
1634            << "lgt : " << length );
1635       }
1636    }
1637
1638    if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1639    {
1640       return true;
1641    }   
1642    return false;
1643 }
1644
1645 /**
1646  * \brief Loads all the needed Dictionaries
1647  * \warning NOT end user intended method !   
1648  */
1649 void Document::Initialize() 
1650 {
1651    RefPubDict = Global::GetDicts()->GetDefaultPubDict();
1652    RefShaDict = NULL;
1653    Filetype   = Unknown;
1654 }
1655
1656 /**
1657  * \brief   Discover what the swap code is (among little endian, big endian,
1658  *          bad little endian, bad big endian).
1659  *          sw is set
1660  * @return false when we are absolutely sure 
1661  *               it's neither ACR-NEMA nor DICOM
1662  *         true  when we hope ours assuptions are OK
1663  */
1664 bool Document::CheckSwap()
1665 {
1666    // The only guaranted way of finding the swap code is to find a
1667    // group tag since we know it's length has to be of four bytes i.e.
1668    // 0x00000004. Finding the swap code in then straigthforward. Trouble
1669    // occurs when we can't find such group...
1670    
1671    uint32_t  x = 4;  // x : for ntohs
1672    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1673    uint32_t  s32;
1674    uint16_t  s16;
1675        
1676    char deb[256];
1677     
1678    // First, compare HostByteOrder and NetworkByteOrder in order to
1679    // determine if we shall need to swap bytes (i.e. the Endian type).
1680    if ( x == ntohs(x) )
1681    {
1682       net2host = true;
1683    }
1684    else
1685    {
1686       net2host = false;
1687    }
1688          
1689    // The easiest case is the one of a 'true' DICOM header, we just have
1690    // to look for the string "DICM" inside the file preamble.
1691    Fp->read(deb, 256);
1692    
1693    char *entCur = deb + 128;
1694    if( memcmp(entCur, "DICM", (size_t)4) == 0 )
1695    {
1696       gdcmVerboseMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1697       
1698       // Group 0002 should always be VR, and the first element 0000
1699       // Let's be carefull (so many wrong headers ...)
1700       // and determine the value representation (VR) : 
1701       // Let's skip to the first element (0002,0000) and check there if we find
1702       // "UL"  - or "OB" if the 1st one is (0002,0001) -,
1703       // in which case we (almost) know it is explicit VR.
1704       // WARNING: if it happens to be implicit VR then what we will read
1705       // is the length of the group. If this ascii representation of this
1706       // length happens to be "UL" then we shall believe it is explicit VR.
1707       // We need to skip :
1708       // * the 128 bytes of File Preamble (often padded with zeroes),
1709       // * the 4 bytes of "DICM" string,
1710       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1711       // i.e. a total of  136 bytes.
1712       entCur = deb + 136;
1713      
1714       // group 0x0002 *is always* Explicit VR Sometimes ,
1715       // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1716       // *Implicit* VR  (see former 'gdcmData/icone.dcm')
1717       
1718       if( memcmp(entCur, "UL", (size_t)2) == 0 ||
1719           memcmp(entCur, "OB", (size_t)2) == 0 ||
1720           memcmp(entCur, "UI", (size_t)2) == 0 ||
1721           memcmp(entCur, "CS", (size_t)2) == 0 )  // CS, to remove later
1722                                                   // when Write DCM *adds*
1723       // FIXME
1724       // Use Document::dicom_vr to test all the possibilities
1725       // instead of just checking for UL, OB and UI !? group 0000 
1726       {
1727          Filetype = ExplicitVR;
1728          gdcmVerboseMacro( "Group 0002 : Explicit Value Representation");
1729       } 
1730       else 
1731       {
1732          Filetype = ImplicitVR;
1733          gdcmVerboseMacro( "Group 0002 :Not an explicit Value Representation;"
1734                         << "Looks like a bugged Header!");
1735       }
1736       
1737       if ( net2host )
1738       {
1739          SwapCode = 4321;
1740          gdcmVerboseMacro( "HostByteOrder != NetworkByteOrder");
1741       }
1742       else 
1743       {
1744          SwapCode = 1234;
1745          gdcmVerboseMacro( "HostByteOrder = NetworkByteOrder");
1746       }
1747       
1748       // Position the file position indicator at first tag 
1749       // (i.e. after the file preamble and the "DICM" string).
1750       Fp->seekg(0, std::ios::beg);
1751       Fp->seekg ( 132L, std::ios::beg);
1752       return true;
1753    } // End of DicomV3
1754
1755    // Alas, this is not a DicomV3 file and whatever happens there is no file
1756    // preamble. We can reset the file position indicator to where the data
1757    // is (i.e. the beginning of the file).
1758    gdcmVerboseMacro( "Not a DICOM Version3 file");
1759    Fp->seekg(0, std::ios::beg);
1760
1761    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1762    // By clean we mean that the length of the first tag is written down.
1763    // If this is the case and since the length of the first group HAS to be
1764    // four (bytes), then determining the proper swap code is straightforward.
1765
1766    entCur = deb + 4;
1767    // We assume the array of char we are considering contains the binary
1768    // representation of a 32 bits integer. Hence the following dirty
1769    // trick :
1770    s32 = *((uint32_t *)(entCur));
1771
1772    switch( s32 )
1773    {
1774       case 0x00040000 :
1775          SwapCode = 3412;
1776          Filetype = ACR;
1777          return true;
1778       case 0x04000000 :
1779          SwapCode = 4321;
1780          Filetype = ACR;
1781          return true;
1782       case 0x00000400 :
1783          SwapCode = 2143;
1784          Filetype = ACR;
1785          return true;
1786       case 0x00000004 :
1787          SwapCode = 1234;
1788          Filetype = ACR;
1789          return true;
1790       default :
1791          // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1792          // It is time for despaired wild guesses. 
1793          // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1794          //  i.e. the 'group length' element is not present :     
1795          
1796          //  check the supposed-to-be 'group number'
1797          //  in ( 0x0001 .. 0x0008 )
1798          //  to determine ' SwapCode' value .
1799          //  Only 0 or 4321 will be possible 
1800          //  (no oportunity to check for the formerly well known
1801          //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
1802          //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-) 
1803          //  the file IS NOT ACR-NEMA nor DICOM V3
1804          //  Find a trick to tell it the caller...
1805       
1806          s16 = *((uint16_t *)(deb));
1807       
1808          switch ( s16 )
1809          {
1810             case 0x0001 :
1811             case 0x0002 :
1812             case 0x0003 :
1813             case 0x0004 :
1814             case 0x0005 :
1815             case 0x0006 :
1816             case 0x0007 :
1817             case 0x0008 :
1818                SwapCode = 1234;
1819                Filetype = ACR;
1820                return true;
1821             case 0x0100 :
1822             case 0x0200 :
1823             case 0x0300 :
1824             case 0x0400 :
1825             case 0x0500 :
1826             case 0x0600 :
1827             case 0x0700 :
1828             case 0x0800 :
1829                SwapCode = 4321;
1830                Filetype = ACR;
1831                return true;
1832             default :
1833                gdcmVerboseMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1834                Filetype = Unknown;
1835                return false;
1836          }
1837    }
1838 }
1839
1840 /**
1841  * \brief Change the Byte Swap code. 
1842  */
1843 void Document::SwitchByteSwapCode() 
1844 {
1845    gdcmVerboseMacro( "Switching Byte Swap code from "<< SwapCode);
1846    if ( SwapCode == 1234 ) 
1847    {
1848       SwapCode = 4321;
1849    }
1850    else if ( SwapCode == 4321 ) 
1851    {
1852       SwapCode = 1234;
1853    }
1854    else if ( SwapCode == 3412 ) 
1855    {
1856       SwapCode = 2143;
1857    }
1858    else if ( SwapCode == 2143 )
1859    {
1860       SwapCode = 3412;
1861    }
1862 }
1863
1864 /**
1865  * \brief  during parsing, Header Elements too long are not loaded in memory 
1866  * @param newSize
1867  */
1868 void Document::SetMaxSizeLoadEntry(long newSize) 
1869 {
1870    if ( newSize < 0 )
1871    {
1872       return;
1873    }
1874    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1875    {
1876       MaxSizeLoadEntry = 0xffffffff;
1877       return;
1878    }
1879    MaxSizeLoadEntry = newSize;
1880 }
1881
1882 /**
1883  * \brief Header Elements too long will not be printed
1884  * \todo  See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE 
1885  * @param newSize
1886  */
1887 void Document::SetMaxSizePrintEntry(long newSize) 
1888 {
1889    if ( newSize < 0 )
1890    {
1891       return;
1892    }
1893    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1894    {
1895       MaxSizePrintEntry = 0xffffffff;
1896       return;
1897    }
1898    MaxSizePrintEntry = newSize;
1899 }
1900
1901
1902 /**
1903  * \brief   Read the next tag but WITHOUT loading it's value
1904  *          (read the 'Group Number', the 'Element Number',
1905  *          gets the Dict Entry
1906  *          gets the VR, gets the length, gets the offset value)
1907  * @return  On succes the newly created DocEntry, NULL on failure.      
1908  */
1909 DocEntry *Document::ReadNextDocEntry()
1910 {
1911    uint16_t group;
1912    uint16_t elem;
1913
1914    try
1915    {
1916       group = ReadInt16();
1917       elem  = ReadInt16();
1918    }
1919    catch ( FormatError e )
1920    {
1921       // We reached the EOF (or an error occured) therefore 
1922       // header parsing has to be considered as finished.
1923       return 0;
1924    }
1925
1926    // Sometimes file contains groups of tags with reversed endianess.
1927    HandleBrokenEndian(group, elem);
1928
1929    // In 'true DICOM' files Group 0002 is always little endian
1930    if ( HasDCMPreamble )
1931       HandleOutOfGroup0002(group, elem);
1932  
1933    std::string vr = FindDocEntryVR();
1934    std::string realVR = vr;
1935
1936    if( vr == GDCM_UNKNOWN)
1937    {
1938       DictEntry *dictEntry = GetDictEntry(group,elem);
1939       if( dictEntry )
1940          realVR = dictEntry->GetVR();
1941    }
1942
1943    DocEntry *newEntry;
1944    if( Global::GetVR()->IsVROfSequence(realVR) )
1945       newEntry = NewSeqEntry(group, elem);
1946    else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
1947       newEntry = NewValEntry(group, elem,vr);
1948    else
1949       newEntry = NewBinEntry(group, elem,vr);
1950
1951    if( vr == GDCM_UNKNOWN )
1952    {
1953       if( Filetype == ExplicitVR )
1954       {
1955          // We thought this was explicit VR, but we end up with an
1956          // implicit VR tag. Let's backtrack.
1957          if ( newEntry->GetGroup() != 0xfffe )
1958          { 
1959             std::string msg;
1960             msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n", 
1961                           newEntry->GetGroup(), newEntry->GetElement());
1962             gdcmVerboseMacro( msg.c_str() );
1963           }
1964       }
1965       newEntry->SetImplicitVR();
1966    }
1967
1968    try
1969    {
1970       FindDocEntryLength(newEntry);
1971    }
1972    catch ( FormatError e )
1973    {
1974       // Call it quits
1975       //std::cout << e;
1976       delete newEntry;
1977       return 0;
1978    }
1979
1980    newEntry->SetOffset(Fp->tellg());  
1981
1982    return newEntry;
1983 }
1984
1985 /**
1986  * \brief   Handle broken private tag from Philips NTSCAN
1987  *          where the endianess is being switch to BigEndian for no
1988  *          apparent reason
1989  * @return  no return
1990  */
1991 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
1992 {
1993    // Endian reversion. Some files contain groups of tags with reversed endianess.
1994    static int reversedEndian = 0;
1995    // try to fix endian switching in the middle of headers
1996    if ((group == 0xfeff) && (elem == 0x00e0))
1997    {
1998      // start endian swap mark for group found
1999      reversedEndian++;
2000      SwitchByteSwapCode();
2001      // fix the tag
2002      group = 0xfffe;
2003      elem  = 0xe000;
2004    } 
2005    else if (group == 0xfffe && elem == 0xe00d && reversedEndian) 
2006    {
2007      // end of reversed endian group
2008      reversedEndian--;
2009      SwitchByteSwapCode();
2010    }
2011 }
2012
2013 /**
2014  * \brief   Group 0002 is always coded Little Endian
2015  *          whatever Transfer Syntax is
2016  * @return  no return
2017  */
2018 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2019 {
2020    // Endian reversion. Some files contain groups of tags with reversed endianess.
2021    if ( !Group0002Parsed && group != 0x0002)
2022    {
2023       Group0002Parsed = true;
2024       // we just came out of group 0002
2025       // if Transfer syntax is Big Endian we have to change CheckSwap
2026
2027       std::string ts = GetTransferSyntax();
2028       if ( !Global::GetTS()->IsTransferSyntax(ts) )
2029       {
2030          gdcmVerboseMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2031          return;
2032       }
2033
2034       // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..." 
2035
2036       if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2037          {
2038             Filetype = ImplicitVR;
2039          }
2040        
2041       // FIXME Strangely, this works with 
2042       //'Implicit VR Transfer Syntax (GE Private)
2043       if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2044       {
2045          gdcmVerboseMacro("Transfer Syntax Name = [" 
2046                         << GetTransferSyntaxName() << "]" );
2047          SwitchByteSwapCode();
2048          group = SwapShort(group);
2049          elem  = SwapShort(elem);
2050       }
2051    }
2052 }
2053
2054 /**
2055  * \brief   Compares two documents, according to \ref DicomDir rules
2056  * \warning Does NOT work with ACR-NEMA files
2057  * \todo    Find a trick to solve the pb (use RET fields ?)
2058  * @param   document
2059  * @return  true if 'smaller'
2060  */
2061 bool Document::operator<(Document &document)
2062 {
2063    // Patient Name
2064    std::string s1 = GetEntryValue(0x0010,0x0010);
2065    std::string s2 = document.GetEntryValue(0x0010,0x0010);
2066    if(s1 < s2)
2067    {
2068       return true;
2069    }
2070    else if( s1 > s2 )
2071    {
2072       return false;
2073    }
2074    else
2075    {
2076       // Patient ID
2077       s1 = GetEntryValue(0x0010,0x0020);
2078       s2 = document.GetEntryValue(0x0010,0x0020);
2079       if ( s1 < s2 )
2080       {
2081          return true;
2082       }
2083       else if ( s1 > s2 )
2084       {
2085          return false;
2086       }
2087       else
2088       {
2089          // Study Instance UID
2090          s1 = GetEntryValue(0x0020,0x000d);
2091          s2 = document.GetEntryValue(0x0020,0x000d);
2092          if ( s1 < s2 )
2093          {
2094             return true;
2095          }
2096          else if( s1 > s2 )
2097          {
2098             return false;
2099          }
2100          else
2101          {
2102             // Serie Instance UID
2103             s1 = GetEntryValue(0x0020,0x000e);
2104             s2 = document.GetEntryValue(0x0020,0x000e);    
2105             if ( s1 < s2 )
2106             {
2107                return true;
2108             }
2109             else if( s1 > s2 )
2110             {
2111                return false;
2112             }
2113          }
2114       }
2115    }
2116    return false;
2117 }
2118
2119 //-----------------------------------------------------------------------------
2120 // Print
2121 /**
2122   * \brief   Prints The Dict Entries of THE public Dicom Dictionary
2123   * @param os ostream to print to
2124   * @return
2125   */  
2126 void Document::PrintPubDict(std::ostream &os)
2127 {
2128    RefPubDict->SetPrintLevel(PrintLevel);
2129    RefPubDict->Print(os);
2130 }
2131
2132 /**
2133   * \brief   Prints The Dict Entries of THE shadow Dicom Dictionary
2134   * @param os ostream to print to
2135   * @return
2136   */
2137 void Document::PrintShaDict(std::ostream &os)
2138 {
2139    RefShaDict->SetPrintLevel(PrintLevel);
2140    RefShaDict->Print(os);
2141 }
2142
2143 //-----------------------------------------------------------------------------
2144 } // end namespace gdcm