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