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