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