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