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