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