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