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