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