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