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