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