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