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