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