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