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