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