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