]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
Extend warning message for debuging purpose.
[gdcm.git] / src / gdcmDocument.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDocument.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/06/24 10:53:46 $
7   Version:   $Revision: 1.251 $
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          // VR = "SQ"
998          unsigned long l = newDocEntry->GetReadLength();          
999          if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1000          {
1001             if ( l == 0xffffffff )
1002             {
1003               delim_mode = true;
1004             }
1005             else
1006             {
1007               delim_mode = false;
1008             }
1009          }
1010  
1011          if ( (LoadMode & NO_SEQ) && ! delim_mode ) // User asked to skip SQ
1012          {
1013             Fp->seekg( l, std::ios::cur);
1014             used = false;
1015             continue;
1016           }
1017          
1018          // no other way to create it ...
1019          newSeqEntry->SetDelimitorMode( delim_mode );
1020
1021          // At the top of the hierarchy, stands a Document. When "set"
1022          // is a Document, then we are building the first depth level.
1023          // Hence the SeqEntry we are building simply has a depth
1024          // level of one:
1025          if ( dynamic_cast< Document* > ( set ) )
1026          {
1027             newSeqEntry->SetDepthLevel( 1 );
1028             newSeqEntry->SetKey( newSeqEntry->GetKey() );
1029          }
1030          // But when "set" is already a SQItem, we are building a nested
1031          // sequence, and hence the depth level of the new SeqEntry
1032          // we are building, is one level deeper:
1033          if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1034          {
1035             newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1036             newSeqEntry->SetKey(  parentSQItem->GetBaseTagKey()
1037                                 + newSeqEntry->GetKey() );
1038          }
1039
1040          if ( l != 0 )
1041          {  // Don't try to parse zero-length sequences
1042             ParseSQ( newSeqEntry, 
1043                      newDocEntry->GetOffset(),
1044                      l, delim_mode);
1045          }
1046          if ( !set->AddEntry( newSeqEntry ) )
1047          {
1048             used = false;
1049          }
1050
1051          if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1052          {
1053             if ( !used )
1054                delete newDocEntry;
1055             break;
1056          }
1057       }
1058
1059       if ( !used )
1060          delete newDocEntry;
1061    }
1062 }
1063
1064 /**
1065  * \brief   Parses a Sequence ( SeqEntry after SeqEntry)
1066  * @return  parsed length for this level
1067  */ 
1068 void Document::ParseSQ( SeqEntry *seqEntry,
1069                         long offset, long l_max, bool delim_mode)
1070 {
1071    int SQItemNumber = 0;
1072    bool dlm_mod;
1073    long offsetStartCurrentSQItem = offset;
1074
1075    while (true)
1076    {
1077       // the first time, we read the fff0,e000 of the first SQItem
1078       DocEntry *newDocEntry = ReadNextDocEntry();
1079
1080       if ( !newDocEntry )
1081       {
1082          // FIXME Should warn user
1083          break;
1084       }
1085       if ( delim_mode )
1086       {
1087          if ( newDocEntry->IsSequenceDelimitor() )
1088          {
1089             seqEntry->SetDelimitationItem( newDocEntry ); 
1090             break;
1091          }
1092       }
1093       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1094       {
1095          delete newDocEntry;
1096          break;
1097       }
1098       // create the current SQItem
1099       SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1100       std::ostringstream newBase;
1101       newBase << seqEntry->GetKey()
1102               << "/"
1103               << SQItemNumber
1104               << "#";
1105       itemSQ->SetBaseTagKey( newBase.str() );
1106       unsigned int l = newDocEntry->GetReadLength();
1107       
1108       if ( l == 0xffffffff )
1109       {
1110          dlm_mod = true;
1111       }
1112       else
1113       {
1114          dlm_mod = false;
1115       }
1116
1117       // Let's try :------------
1118       // remove fff0,e000, created out of the SQItem
1119       delete newDocEntry;
1120       Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1121       // fill up the current SQItem, starting at the beginning of fff0,e000
1122       ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1123       offsetStartCurrentSQItem = Fp->tellg();
1124       // end try -----------------
1125  
1126       seqEntry->AddSQItem( itemSQ, SQItemNumber ); 
1127       SQItemNumber++;
1128       if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1129       {
1130          break;
1131       }
1132    }
1133 }
1134
1135 /**
1136  * \brief   Loads the element content if its length doesn't exceed
1137  *          the value specified with Document::SetMaxSizeLoadEntry()
1138  * @param   entry Header Entry (Dicom Element) to be dealt with
1139  */
1140 void Document::LoadDocEntry(DocEntry *entry)
1141 {
1142    uint16_t group  = entry->GetGroup();
1143    std::string  vr = entry->GetVR();
1144    uint32_t length = entry->GetLength();
1145
1146    Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1147
1148    // A SeQuence "contains" a set of Elements.  
1149    //          (fffe e000) tells us an Element is beginning
1150    //          (fffe e00d) tells us an Element just ended
1151    //          (fffe e0dd) tells us the current SeQuence just ended
1152    if ( group == 0xfffe )
1153    {
1154       // NO more value field for SQ !
1155       return;
1156    }
1157
1158    // When the length is zero things are easy:
1159    if ( length == 0 )
1160    {
1161       ((ValEntry *)entry)->SetValue("");
1162       return;
1163    }
1164
1165    // The elements whose length is bigger than the specified upper bound
1166    // are not loaded. Instead we leave a short notice of the offset of
1167    // the element content and it's length.
1168
1169    std::ostringstream s;
1170    if (length > MaxSizeLoadEntry)
1171    {
1172       if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1173       {  
1174          s << GDCM_NOTLOADED;
1175          s << " Ad.:" << (long)entry->GetOffset();
1176          s << " x(" << std::hex << entry->GetOffset() << ")";
1177          s << std::dec;
1178          s << " Lgt:"  << entry->GetLength();
1179          s << " x(" << std::hex << entry->GetLength() << ")";
1180          binEntryPtr->SetValue(s.str());
1181       }
1182       else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1183       {
1184          s << GDCM_NOTLOADED;  
1185          s << " Address:" << (long)entry->GetOffset();
1186          s << " Length:"  << entry->GetLength();
1187          s << " x(" << std::hex << entry->GetLength() << ")";
1188          valEntryPtr->SetValue(s.str());
1189       }
1190       else
1191       {
1192          // fusible
1193          gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1194                       << "nor a ValEntry ?! Should never print that !" );
1195       }
1196
1197       // to be sure we are at the end of the value ...
1198       Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1199                 std::ios::beg);
1200       return;
1201    }
1202
1203    // When we find a BinEntry not very much can be done :
1204    if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1205    {
1206       s << GDCM_BINLOADED;
1207       binEntryPtr->SetValue(s.str());
1208       LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1209       return;
1210    }
1211
1212    if ( IsDocEntryAnInteger(entry) )
1213    {   
1214       uint32_t NewInt;
1215       int nbInt;
1216       // When short integer(s) are expected, read and convert the following 
1217       // (n * 2) characters properly i.e. consider them as short integers as
1218       // opposed to strings.
1219       // Elements with Value Multiplicity > 1
1220       // contain a set of integers (not a single one)       
1221       if (vr == "US" || vr == "SS")
1222       {
1223          nbInt = length / 2;
1224          NewInt = ReadInt16();
1225          s << NewInt;
1226          if (nbInt > 1)
1227          {
1228             for (int i=1; i < nbInt; i++)
1229             {
1230                s << '\\';
1231                NewInt = ReadInt16();
1232                s << NewInt;
1233             }
1234          }
1235       }
1236       // See above comment on multiple integers (mutatis mutandis).
1237       else if (vr == "UL" || vr == "SL")
1238       {
1239          nbInt = length / 4;
1240          NewInt = ReadInt32();
1241          s << NewInt;
1242          if (nbInt > 1)
1243          {
1244             for (int i=1; i < nbInt; i++)
1245             {
1246                s << '\\';
1247                NewInt = ReadInt32();
1248                s << NewInt;
1249             }
1250          }
1251       }
1252 #ifdef GDCM_NO_ANSI_STRING_STREAM
1253       s << std::ends; // to avoid oddities on Solaris
1254 #endif //GDCM_NO_ANSI_STRING_STREAM
1255
1256       ((ValEntry *)entry)->SetValue(s.str());
1257       return;
1258    }
1259    
1260   // FIXME: We need an additional byte for storing \0 that is not on disk
1261    char *str = new char[length+1];
1262    Fp->read(str, (size_t)length);
1263    str[length] = '\0'; //this is only useful when length is odd
1264    // Special DicomString call to properly handle \0 and even length
1265    std::string newValue;
1266    if ( length % 2 )
1267    {
1268       newValue = Util::DicomString(str, length+1);
1269       gdcmWarningMacro("Warning: bad length: " << length <<
1270                        " For string :" <<  newValue.c_str()); 
1271       // Since we change the length of string update it length
1272       //entry->SetReadLength(length+1);
1273    }
1274    else
1275    {
1276       newValue = Util::DicomString(str, length);
1277    }
1278    delete[] str;
1279
1280    if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1281    {
1282       if ( Fp->fail() || Fp->eof())
1283       {
1284          if ( Fp->fail() )
1285             gdcmWarningMacro("--> fail");
1286
1287          gdcmWarningMacro("Unread element value " << valEntry->GetKey() 
1288                           << " lgt : " << valEntry->GetReadLength() 
1289                           << " at " << std::hex << valEntry->GetOffset());
1290          valEntry->SetValue(GDCM_UNREAD);
1291          return;
1292       }
1293
1294       if ( vr == "UI" )
1295       {
1296          // Because of correspondance with the VR dic
1297          valEntry->SetValue(newValue);
1298       }
1299       else
1300       {
1301          valEntry->SetValue(newValue);
1302       }
1303    }
1304    else
1305    {
1306       gdcmWarningMacro("Should have a ValEntry, here ! " << valEntry->GetKey() 
1307                           << " lgt : " << valEntry->GetReadLength() 
1308                           << " at " << std::hex << valEntry->GetOffset());
1309    }
1310 }
1311
1312 /**
1313  * \brief  Find the value Length of the passed Header Entry
1314  * @param  entry Header Entry whose length of the value shall be loaded. 
1315  */
1316 void Document::FindDocEntryLength( DocEntry *entry )
1317    throw ( FormatError )
1318 {
1319    std::string  vr  = entry->GetVR();
1320    uint16_t length16;       
1321    
1322    if ( Filetype == ExplicitVR && !entry->IsImplicitVR() ) 
1323    {
1324       if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT" || vr == "UN" ) 
1325       {
1326          // The following reserved two bytes (see PS 3.5-2003, section
1327          // "7.1.2 Data element structure with explicit vr", p 27) must be
1328          // skipped before proceeding on reading the length on 4 bytes.
1329          Fp->seekg( 2L, std::ios::cur);
1330          uint32_t length32 = ReadInt32();
1331
1332          if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff ) 
1333          {
1334             uint32_t lengthOB;
1335             try 
1336             {
1337                lengthOB = FindDocEntryLengthOBOrOW();
1338             }
1339             catch ( FormatUnexpected )
1340             {
1341                // Computing the length failed (this happens with broken
1342                // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1343                // chance to get the pixels by deciding the element goes
1344                // until the end of the file. Hence we artificially fix the
1345                // the length and proceed.
1346                long currentPosition = Fp->tellg();
1347                Fp->seekg(0L,std::ios::end);
1348
1349                long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1350                Fp->seekg(currentPosition, std::ios::beg);
1351
1352                entry->SetReadLength(lengthUntilEOF);
1353                entry->SetLength(lengthUntilEOF);
1354                return;
1355             }
1356             entry->SetReadLength(lengthOB);
1357             entry->SetLength(lengthOB);
1358             return;
1359          }
1360          FixDocEntryFoundLength(entry, length32); 
1361          return;
1362       }
1363
1364       // Length is encoded on 2 bytes.
1365       length16 = ReadInt16();
1366   
1367       // 0xffff means that we deal with 'No Length' Sequence 
1368       //        or 'No Length' SQItem
1369       if ( length16 == 0xffff) 
1370       {           
1371          length16 = 0;
1372       }
1373       FixDocEntryFoundLength( entry, (uint32_t)length16 );
1374       return;
1375    }
1376    else
1377    {
1378       // Either implicit VR or a non DICOM conformal (see note below) explicit
1379       // VR that ommited the VR of (at least) this element. Farts happen.
1380       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1381       // on Data elements "Implicit and Explicit VR Data Elements shall
1382       // not coexist in a Data Set and Data Sets nested within it".]
1383       // Length is on 4 bytes.
1384
1385      // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1386      // even if Transfer Syntax is 'Implicit VR ...' 
1387       
1388       FixDocEntryFoundLength( entry, ReadInt32() );
1389       return;
1390    }
1391 }
1392
1393 /**
1394  * \brief  Find the Length till the next sequence delimiter
1395  * \warning NOT end user intended method !
1396  * @return 
1397  */
1398 uint32_t Document::FindDocEntryLengthOBOrOW()
1399    throw( FormatUnexpected )
1400 {
1401    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1402    long positionOnEntry = Fp->tellg();
1403    bool foundSequenceDelimiter = false;
1404    uint32_t totalLength = 0;
1405
1406    while ( !foundSequenceDelimiter )
1407    {
1408       uint16_t group;
1409       uint16_t elem;
1410       try
1411       {
1412          group = ReadInt16();
1413          elem  = ReadInt16();   
1414       }
1415       catch ( FormatError )
1416       {
1417          throw FormatError("Unexpected end of file encountered during ",
1418                            "Document::FindDocEntryLengthOBOrOW()");
1419       }
1420       // We have to decount the group and element we just read
1421       totalLength += 4;     
1422       if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1423       {
1424          long filePosition = Fp->tellg();
1425          gdcmWarningMacro( 
1426               "Neither an Item tag nor a Sequence delimiter tag on :" 
1427            << std::hex << group << " , " << elem 
1428            << ") -before- position x(" << filePosition << ")" );
1429   
1430          Fp->seekg(positionOnEntry, std::ios::beg);
1431          throw FormatUnexpected( 
1432                "Neither an Item tag nor a Sequence delimiter tag.");
1433       }
1434       if ( elem == 0xe0dd )
1435       {
1436          foundSequenceDelimiter = true;
1437       }
1438       uint32_t itemLength = ReadInt32();
1439       // We add 4 bytes since we just read the ItemLength with ReadInt32
1440       totalLength += itemLength + 4;
1441       SkipBytes(itemLength);
1442       
1443       if ( foundSequenceDelimiter )
1444       {
1445          break;
1446       }
1447    }
1448    Fp->seekg( positionOnEntry, std::ios::beg);
1449    return totalLength;
1450 }
1451
1452 /**
1453  * \brief     Find the Value Representation of the current Dicom Element.
1454  * @return    Value Representation of the current Entry
1455  */
1456 std::string Document::FindDocEntryVR()
1457 {
1458    if ( Filetype != ExplicitVR )
1459       return GDCM_UNKNOWN;
1460
1461    long positionOnEntry = Fp->tellg();
1462    // Warning: we believe this is explicit VR (Value Representation) because
1463    // we used a heuristic that found "UL" in the first tag. Alas this
1464    // doesn't guarantee that all the tags will be in explicit VR. In some
1465    // cases (see e-film filtered files) one finds implicit VR tags mixed
1466    // within an explicit VR file. Hence we make sure the present tag
1467    // is in explicit VR and try to fix things if it happens not to be
1468    // the case.
1469
1470    char vr[3];
1471    Fp->read (vr, (size_t)2);
1472    vr[2] = 0;
1473
1474    if ( !CheckDocEntryVR(vr) )
1475    {
1476       Fp->seekg(positionOnEntry, std::ios::beg);
1477       return GDCM_UNKNOWN;
1478    }
1479    return vr;
1480 }
1481
1482 /**
1483  * \brief     Check the correspondance between the VR of the header entry
1484  *            and the taken VR. If they are different, the header entry is 
1485  *            updated with the new VR.
1486  * @param     vr    Dicom Value Representation
1487  * @return    false if the VR is incorrect of if the VR isn't referenced
1488  *            otherwise, it returns true
1489 */
1490 bool Document::CheckDocEntryVR(VRKey vr)
1491 {
1492    if ( !Global::GetVR()->IsValidVR(vr) )
1493       return false;
1494
1495    return true; 
1496 }
1497
1498 /**
1499  * \brief   Get the transformed value of the header entry. The VR value 
1500  *          is used to define the transformation to operate on the value
1501  * \warning NOT end user intended method !
1502  * @param   entry entry to tranform
1503  * @return  Transformed entry value
1504  */
1505 std::string Document::GetDocEntryValue(DocEntry *entry)
1506 {
1507    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1508    {
1509       std::string val = ((ValEntry *)entry)->GetValue();
1510       std::string vr  = entry->GetVR();
1511       uint32_t length = entry->GetLength();
1512       std::ostringstream s;
1513       int nbInt;
1514
1515       // When short integer(s) are expected, read and convert the following 
1516       // n * 2 bytes properly i.e. as a multivaluated strings
1517       // (each single value is separated fromthe next one by '\'
1518       // as usual for standard multivaluated filels
1519       // Elements with Value Multiplicity > 1
1520       // contain a set of short integers (not a single one) 
1521    
1522       if ( vr == "US" || vr == "SS" )
1523       {
1524          uint16_t newInt16;
1525
1526          nbInt = length / 2;
1527          for (int i=0; i < nbInt; i++) 
1528          {
1529             if ( i != 0 )
1530             {
1531                s << '\\';
1532             }
1533             newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1534             newInt16 = SwapShort( newInt16 );
1535             s << newInt16;
1536          }
1537       }
1538
1539       // When integer(s) are expected, read and convert the following 
1540       // n * 4 bytes properly i.e. as a multivaluated strings
1541       // (each single value is separated fromthe next one by '\'
1542       // as usual for standard multivaluated filels
1543       // Elements with Value Multiplicity > 1
1544       // contain a set of integers (not a single one) 
1545       else if ( vr == "UL" || vr == "SL" )
1546       {
1547          uint32_t newInt32;
1548
1549          nbInt = length / 4;
1550          for (int i=0; i < nbInt; i++) 
1551          {
1552             if ( i != 0)
1553             {
1554                s << '\\';
1555             }
1556             newInt32 = ( val[4*i+0] & 0xFF )
1557                     + (( val[4*i+1] & 0xFF ) <<  8 )
1558                     + (( val[4*i+2] & 0xFF ) << 16 )
1559                     + (( val[4*i+3] & 0xFF ) << 24 );
1560             newInt32 = SwapLong( newInt32 );
1561             s << newInt32;
1562          }
1563       }
1564 #ifdef GDCM_NO_ANSI_STRING_STREAM
1565       s << std::ends; // to avoid oddities on Solaris
1566 #endif //GDCM_NO_ANSI_STRING_STREAM
1567       return s.str();
1568    }
1569    return ((ValEntry *)entry)->GetValue();
1570 }
1571
1572 /**
1573  * \brief   Get the reverse transformed value of the header entry. The VR 
1574  *          value is used to define the reverse transformation to operate on
1575  *          the value
1576  * \warning NOT end user intended method !
1577  * @param   entry Entry to reverse transform
1578  * @return  Reverse transformed entry value
1579  */
1580 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1581 {
1582    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1583    {
1584       std::string vr = entry->GetVR();
1585       std::vector<std::string> tokens;
1586       std::ostringstream s;
1587
1588       if ( vr == "US" || vr == "SS" ) 
1589       {
1590          uint16_t newInt16;
1591
1592          tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1593          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1594          for (unsigned int i=0; i<tokens.size(); i++) 
1595          {
1596             newInt16 = atoi(tokens[i].c_str());
1597             s << (  newInt16        & 0xFF ) 
1598               << (( newInt16 >> 8 ) & 0xFF );
1599          }
1600          tokens.clear();
1601       }
1602       if ( vr == "UL" || vr == "SL")
1603       {
1604          uint32_t newInt32;
1605
1606          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1607          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1608          for (unsigned int i=0; i<tokens.size();i++) 
1609          {
1610             newInt32 = atoi(tokens[i].c_str());
1611             s << (char)(  newInt32         & 0xFF ) 
1612               << (char)(( newInt32 >>  8 ) & 0xFF )
1613               << (char)(( newInt32 >> 16 ) & 0xFF )
1614               << (char)(( newInt32 >> 24 ) & 0xFF );
1615          }
1616          tokens.clear();
1617       }
1618
1619 #ifdef GDCM_NO_ANSI_STRING_STREAM
1620       s << std::ends; // to avoid oddities on Solaris
1621 #endif //GDCM_NO_ANSI_STRING_STREAM
1622       return s.str();
1623    }
1624
1625    return ((ValEntry *)entry)->GetValue();
1626 }
1627
1628 /**
1629  * \brief   Skip a given Header Entry 
1630  * \warning NOT end user intended method !
1631  * @param   entry entry to skip
1632  */
1633 void Document::SkipDocEntry(DocEntry *entry) 
1634 {
1635    SkipBytes(entry->GetLength());
1636 }
1637
1638 /**
1639  * \brief   Skips to the beginning of the next Header Entry 
1640  * \warning NOT end user intended method !
1641  * @param   currentDocEntry entry to skip
1642  */
1643 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry) 
1644 {
1645    Fp->seekg((long)(currentDocEntry->GetOffset()),     std::ios::beg);
1646    if (currentDocEntry->GetGroup() != 0xfffe)  // for fffe pb
1647       Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1648 }
1649
1650 /**
1651  * \brief   When the length of an element value is obviously wrong (because
1652  *          the parser went Jabberwocky) one can hope improving things by
1653  *          applying some heuristics.
1654  * @param   entry entry to check
1655  * @param   foundLength first assumption about length    
1656  */
1657 void Document::FixDocEntryFoundLength(DocEntry *entry,
1658                                       uint32_t foundLength)
1659 {
1660    entry->SetReadLength( foundLength ); // will be updated only if a bug is found        
1661    if ( foundLength == 0xffffffff)
1662    {
1663       foundLength = 0;
1664    }
1665    
1666    uint16_t gr   = entry->GetGroup();
1667    uint16_t elem = entry->GetElement(); 
1668      
1669    if ( foundLength % 2)
1670    {
1671       gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength 
1672         <<  " in x(" << std::hex << gr << "," << elem <<")");
1673    }
1674       
1675    //////// Fix for some naughty General Electric images.
1676    // Allthough not recent many such GE corrupted images are still present
1677    // on Creatis hard disks. Hence this fix shall remain when such images
1678    // are no longer in use (we are talking a few years, here)...
1679    // Note: XMedCon probably uses such a trick since it is able to read
1680    //       those pesky GE images ...
1681    if ( foundLength == 13)
1682    {
1683       // Only happens for this length !
1684       if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1685       {
1686          foundLength = 10;
1687          entry->SetReadLength(10); // a bug is to be fixed !?
1688       }
1689    }
1690
1691    //////// Fix for some brain-dead 'Leonardo' Siemens images.
1692    // Occurence of such images is quite low (unless one leaves close to a
1693    // 'Leonardo' source. Hence, one might consider commenting out the
1694    // following fix on efficiency reasons.
1695    else if ( gr   == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1696    {
1697       foundLength = 4;
1698       entry->SetReadLength(4); // a bug is to be fixed !?
1699    } 
1700  
1701    else if ( entry->GetVR() == "SQ" )
1702    {
1703       foundLength = 0;      // ReadLength is unchanged 
1704    } 
1705     
1706    //////// We encountered a 'delimiter' element i.e. a tag of the form 
1707    // "fffe|xxxx" which is just a marker. Delimiters length should not be
1708    // taken into account.
1709    else if ( gr == 0xfffe )
1710    {    
1711      // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1712      // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1713      // causes extra troubles...
1714      if ( entry->GetElement() != 0x0000 )
1715      {
1716         foundLength = 0;
1717      }
1718    }            
1719    entry->SetLength(foundLength);
1720 }
1721
1722 /**
1723  * \brief   Apply some heuristics to predict whether the considered 
1724  *          element value contains/represents an integer or not.
1725  * @param   entry The element value on which to apply the predicate.
1726  * @return  The result of the heuristical predicate.
1727  */
1728 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1729 {
1730    uint16_t elem         = entry->GetElement();
1731    uint16_t group        = entry->GetGroup();
1732    const std::string &vr = entry->GetVR();
1733    uint32_t length       = entry->GetLength();
1734
1735    // When we have some semantics on the element we just read, and if we
1736    // a priori know we are dealing with an integer, then we shall be
1737    // able to swap it's element value properly.
1738    if ( elem == 0 )  // This is the group length of the group
1739    {  
1740       if ( length == 4 )
1741       {
1742          return true;
1743       }
1744       else 
1745       {
1746          // Allthough this should never happen, still some images have a
1747          // corrupted group length [e.g. have a glance at offset x(8336) of
1748          // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1749          // Since for dicom compliant and well behaved headers, the present
1750          // test is useless (and might even look a bit paranoid), when we
1751          // encounter such an ill-formed image, we simply display a warning
1752          // message and proceed on parsing (while crossing fingers).
1753          long filePosition = Fp->tellg();
1754          gdcmWarningMacro( "Erroneous Group Length element length  on : (" 
1755            << std::hex << group << " , " << elem
1756            << ") -before- position x(" << filePosition << ")"
1757            << "lgt : " << length );
1758       }
1759    }
1760
1761    if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1762    {
1763       return true;
1764    }   
1765    return false;
1766 }
1767
1768 /**
1769  * \brief   Discover what the swap code is (among little endian, big endian,
1770  *          bad little endian, bad big endian).
1771  *          sw is set
1772  * @return false when we are absolutely sure 
1773  *               it's neither ACR-NEMA nor DICOM
1774  *         true  when we hope ours assuptions are OK
1775  */
1776 bool Document::CheckSwap()
1777 {   
1778    uint32_t  s32;
1779    uint16_t  s16;
1780        
1781    char deb[256];
1782     
1783    // First, compare HostByteOrder and NetworkByteOrder in order to
1784    // determine if we shall need to swap bytes (i.e. the Endian type).
1785    bool net2host = Util::IsCurrentProcessorBigEndian();
1786          
1787    // The easiest case is the one of a 'true' DICOM header, we just have
1788    // to look for the string "DICM" inside the file preamble.
1789    Fp->read(deb, 256);
1790    
1791    char *entCur = deb + 128;
1792    if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1793    {
1794       gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1795       
1796       // Group 0002 should always be VR, and the first element 0000
1797       // Let's be carefull (so many wrong headers ...)
1798       // and determine the value representation (VR) : 
1799       // Let's skip to the first element (0002,0000) and check there if we find
1800       // "UL"  - or "OB" if the 1st one is (0002,0001) -,
1801       // in which case we (almost) know it is explicit VR.
1802       // WARNING: if it happens to be implicit VR then what we will read
1803       // is the length of the group. If this ascii representation of this
1804       // length happens to be "UL" then we shall believe it is explicit VR.
1805       // We need to skip :
1806       // * the 128 bytes of File Preamble (often padded with zeroes),
1807       // * the 4 bytes of "DICM" string,
1808       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1809       // i.e. a total of  136 bytes.
1810       entCur = deb + 136;
1811      
1812       // group 0x0002 *is always* Explicit VR Sometimes ,
1813       // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1814       // *Implicit* VR  (see former 'gdcmData/icone.dcm')
1815       
1816       if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1817            memcmp(entCur, "OB", (size_t)2) == 0 ||
1818            memcmp(entCur, "UI", (size_t)2) == 0 ||
1819            memcmp(entCur, "CS", (size_t)2) == 0 )  // CS, to remove later
1820                                                    // when Write DCM *adds*
1821       // FIXME
1822       // Use Document::dicom_vr to test all the possibilities
1823       // instead of just checking for UL, OB and UI !? group 0000 
1824       {
1825          Filetype = ExplicitVR;
1826          gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1827       } 
1828       else 
1829       {
1830          Filetype = ImplicitVR;
1831          gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1832                         << "Looks like a bugged Header!");
1833       }
1834       
1835       if ( net2host )
1836       {
1837          SwapCode = 4321;
1838          gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
1839       }
1840       else 
1841       {
1842          SwapCode = 1234;
1843          gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
1844       }
1845       
1846       // Position the file position indicator at first tag 
1847       // (i.e. after the file preamble and the "DICM" string).
1848
1849       Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
1850
1851       Fp->seekg ( 132L, std::ios::beg);
1852       return true;
1853    } // ------------------------------- End of DicomV3 ----------------
1854
1855    // Alas, this is not a DicomV3 file and whatever happens there is no file
1856    // preamble. We can reset the file position indicator to where the data
1857    // is (i.e. the beginning of the file).
1858
1859    gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1860
1861    Fp->seekg(0, std::ios::beg);
1862
1863    // Let's check 'No Preamble Dicom File' :
1864    // Should start with group 0x0002
1865    // and be Explicit Value Representation
1866
1867    s16 = *((uint16_t *)(deb));
1868    SwapCode = 0;     
1869    switch ( s16 )
1870    {
1871       case 0x0002 :
1872          SwapCode = 1234;
1873          entCur = deb + 4;
1874          break;
1875       case 0x0200 :
1876          SwapCode = 4321;
1877          entCur = deb + 6;
1878     } 
1879
1880    if ( SwapCode != 0 )
1881    {
1882       if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1883            memcmp(entCur, "OB", (size_t)2) == 0 ||
1884            memcmp(entCur, "UI", (size_t)2) == 0 ||
1885            memcmp(entCur, "SH", (size_t)2) == 0 ||
1886            memcmp(entCur, "AE", (size_t)2) == 0 ||
1887            memcmp(entCur, "OB", (size_t)2) == 0 )
1888          {
1889             Filetype = ExplicitVR;
1890             gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1891             return true;
1892           }
1893     }
1894 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1895
1896    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1897    // By clean we mean that the length of the first group is written down.
1898    // If this is the case and since the length of the first group HAS to be
1899    // four (bytes), then determining the proper swap code is straightforward.
1900
1901    entCur = deb + 4;
1902    // We assume the array of char we are considering contains the binary
1903    // representation of a 32 bits integer. Hence the following dirty
1904    // trick :
1905    s32 = *((uint32_t *)(entCur));
1906    switch( s32 )
1907    {
1908       case 0x00040000 :
1909          SwapCode = 3412;
1910          Filetype = ACR;
1911          return true;
1912       case 0x04000000 :
1913          SwapCode = 4321;
1914          Filetype = ACR;
1915          return true;
1916       case 0x00000400 :
1917          SwapCode = 2143;
1918          Filetype = ACR;
1919          return true;
1920       case 0x00000004 :
1921          SwapCode = 1234;
1922          Filetype = ACR;
1923          return true;
1924       default :
1925          // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1926          // It is time for despaired wild guesses. 
1927          // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1928          //  i.e. the 'group length' element is not present :     
1929          
1930          //  check the supposed-to-be 'group number'
1931          //  in ( 0x0001 .. 0x0008 )
1932          //  to determine ' SwapCode' value .
1933          //  Only 0 or 4321 will be possible 
1934          //  (no oportunity to check for the formerly well known
1935          //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
1936          //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-) 
1937          //  the file IS NOT ACR-NEMA nor DICOM V3
1938          //  Find a trick to tell it the caller...
1939       
1940          s16 = *((uint16_t *)(deb));
1941       
1942          switch ( s16 )
1943          {
1944             case 0x0001 :
1945             case 0x0002 :
1946             case 0x0003 :
1947             case 0x0004 :
1948             case 0x0005 :
1949             case 0x0006 :
1950             case 0x0007 :
1951             case 0x0008 :
1952                SwapCode = 1234;
1953                Filetype = ACR;
1954                return true;
1955             case 0x0100 :
1956             case 0x0200 :
1957             case 0x0300 :
1958             case 0x0400 :
1959             case 0x0500 :
1960             case 0x0600 :
1961             case 0x0700 :
1962             case 0x0800 :
1963                SwapCode = 4321;
1964                Filetype = ACR;
1965                return true;
1966             default :
1967                gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1968                Filetype = Unknown;
1969                return false;
1970          }
1971    }
1972 }
1973
1974 /**
1975  * \brief Change the Byte Swap code. 
1976  */
1977 void Document::SwitchByteSwapCode() 
1978 {
1979    gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode
1980                      << " at :" <<std::hex << Fp->tellg() );
1981    if ( SwapCode == 1234 ) 
1982    {
1983       SwapCode = 4321;
1984    }
1985    else if ( SwapCode == 4321 ) 
1986    {
1987       SwapCode = 1234;
1988    }
1989    else if ( SwapCode == 3412 ) 
1990    {
1991       SwapCode = 2143;
1992    }
1993    else if ( SwapCode == 2143 )
1994    {
1995       SwapCode = 3412;
1996    }
1997 }
1998
1999 /**
2000  * \brief  during parsing, Header Elements too long are not loaded in memory 
2001  * @param newSize new size
2002  */
2003 void Document::SetMaxSizeLoadEntry(long newSize) 
2004 {
2005    if ( newSize < 0 )
2006    {
2007       return;
2008    }
2009    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2010    {
2011       MaxSizeLoadEntry = 0xffffffff;
2012       return;
2013    }
2014    MaxSizeLoadEntry = newSize;
2015 }
2016
2017 /**
2018  * \brief   Read the next tag but WITHOUT loading it's value
2019  *          (read the 'Group Number', the 'Element Number',
2020  *          gets the Dict Entry
2021  *          gets the VR, gets the length, gets the offset value)
2022  * @return  On succes the newly created DocEntry, NULL on failure.      
2023  */
2024 DocEntry *Document::ReadNextDocEntry()
2025 {
2026    uint16_t group;
2027    uint16_t elem;
2028
2029    try
2030    {
2031       group = ReadInt16();
2032       elem  = ReadInt16();
2033    }
2034    catch ( FormatError e )
2035    {
2036       // We reached the EOF (or an error occured) therefore 
2037       // header parsing has to be considered as finished.
2038       return 0;
2039    }
2040
2041    // Sometimes file contains groups of tags with reversed endianess.
2042    HandleBrokenEndian(group, elem);
2043
2044    // In 'true DICOM' files Group 0002 is always little endian
2045    if ( HasDCMPreamble )
2046       HandleOutOfGroup0002(group, elem);
2047  
2048    std::string vr = FindDocEntryVR();
2049    std::string realVR = vr;
2050
2051    if ( vr == GDCM_UNKNOWN )
2052    {
2053       if ( elem == 0x0000 ) // Group Length
2054          realVR = "UL";     // must be UL
2055       else
2056       {
2057          DictEntry *dictEntry = GetDictEntry(group,elem);
2058          if ( dictEntry )
2059             realVR = dictEntry->GetVR();
2060       }
2061    }
2062
2063    DocEntry *newEntry;
2064    if ( Global::GetVR()->IsVROfSequence(realVR) )
2065       newEntry = NewSeqEntry(group, elem);
2066    else if ( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2067       newEntry = NewValEntry(group, elem,vr);
2068    else
2069       newEntry = NewBinEntry(group, elem,vr);
2070
2071    if ( vr == GDCM_UNKNOWN )
2072    {
2073       if ( Filetype == ExplicitVR )
2074       {
2075          // We thought this was explicit VR, but we end up with an
2076          // implicit VR tag. Let's backtrack.
2077          if ( newEntry->GetGroup() != 0xfffe )
2078          { 
2079             std::string msg;
2080             int offset = Fp->tellg();
2081             msg = Util::Format("Entry (%04x,%04x) at %x should be Explicit VR\n", 
2082                           newEntry->GetGroup(), newEntry->GetElement(), offset );
2083             gdcmWarningMacro( msg.c_str() );
2084           }
2085       }
2086       newEntry->SetImplicitVR();
2087    }
2088
2089    try
2090    {
2091       FindDocEntryLength(newEntry);
2092    }
2093    catch ( FormatError e )
2094    {
2095       // Call it quits
2096       delete newEntry;
2097       return 0;
2098    }
2099
2100    newEntry->SetOffset(Fp->tellg());  
2101
2102    return newEntry;
2103 }
2104
2105 /**
2106  * \brief   Handle broken private tag from Philips NTSCAN
2107  *          where the endianess is being switch to BigEndian for no
2108  *          apparent reason
2109  * @return  no return
2110  */
2111 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2112 {
2113    // Endian reversion. Some files contain groups of tags with reversed endianess.
2114    static int reversedEndian = 0;
2115    // try to fix endian switching in the middle of headers
2116    if ((group == 0xfeff) && (elem == 0x00e0))
2117    {
2118      // start endian swap mark for group found
2119      reversedEndian++;
2120      SwitchByteSwapCode();
2121      // fix the tag
2122      group = 0xfffe;
2123      elem  = 0xe000;
2124    } 
2125    else if (group == 0xfffe && elem == 0xe00d && reversedEndian) 
2126    {
2127      // end of reversed endian group
2128      reversedEndian--;
2129      SwitchByteSwapCode();
2130    }
2131 }
2132
2133 /**
2134  * \brief   Group 0002 is always coded Little Endian
2135  *          whatever Transfer Syntax is
2136  * @return  no return
2137  */
2138 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2139 {
2140    // Endian reversion. Some files contain groups of tags with reversed endianess.
2141    if ( !Group0002Parsed && group != 0x0002)
2142    {
2143       Group0002Parsed = true;
2144       // we just came out of group 0002
2145       // if Transfer syntax is Big Endian we have to change CheckSwap
2146
2147       std::string ts = GetTransferSyntax();
2148       if ( !Global::GetTS()->IsTransferSyntax(ts) )
2149       {
2150          gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2151          return;
2152       }
2153
2154       // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..." 
2155
2156       if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2157          {
2158             Filetype = ImplicitVR;
2159          }
2160        
2161       // FIXME Strangely, this works with 
2162       //'Implicit VR Transfer Syntax (GE Private)
2163       if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2164       {
2165          gdcmWarningMacro("Transfer Syntax Name = [" 
2166                         << GetTransferSyntaxName() << "]" );
2167          SwitchByteSwapCode();
2168          group = SwapShort(group);
2169          elem  = SwapShort(elem);
2170       }
2171    }
2172 }
2173
2174 //-----------------------------------------------------------------------------
2175 // Print
2176
2177 //-----------------------------------------------------------------------------
2178 } // end namespace gdcm