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