]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
In order to allow to use current version (1.3) of gdcm *and* ITK (that includes
[gdcm.git] / src / gdcmDocument.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDocument.cxx,v $
5   Language:  C++
6   Date:      $Date: 2007/05/23 14:18:09 $
7   Version:   $Revision: 1.358 $
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 }
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_NAME_SPACE::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  *         or if the file starts with an ACR-NEMA look-like element.
586  * @return The FILE pointer on success, 0 on failure. 
587  */
588 std::ifstream *Document::OpenFile()
589 {
590    HasDCMPreamble = false;
591    if (Filename.length() == 0) 
592    {
593       return 0;
594    }
595
596    if ( Fp )
597    {
598       gdcmDebugMacro( "File already open: " << Filename.c_str());
599       CloseFile();
600    }
601
602    Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
603    if ( ! *Fp )
604    {
605    // Don't user gdcmErrorMacro :
606    // a spurious message will appear when you use, for instance 
607    // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
608    // to create outputFileName.
609    
610    // FIXME : if the upper comment is still usefull 
611    //         --> the constructor is not so good ...
612    
613       gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
614       delete Fp;
615       Fp = 0;
616       return 0;
617       //exit(1); // No function is allowed to leave the application instead
618                  // of warning the caller
619    }
620  
621    uint16_t zero = 0;
622    Fp->read((char*)&zero, (size_t)2);
623    if ( Fp->eof() )
624    {
625       CloseFile();
626       return 0;
627    }
628  
629    //-- DICOM --
630    Fp->seekg(126L, std::ios::cur);  // Once per Document
631    char dicm[4]; // = {' ',' ',' ',' '};
632    Fp->read(dicm,  (size_t)4);
633    if ( Fp->eof() )
634    {
635       CloseFile();
636       return 0;
637    }
638    
639    if ( memcmp(dicm, "DICM", 4) == 0 )
640    {
641       HasDCMPreamble = true;
642       return Fp;
643    }
644
645    //-- Broken ACR or DICOM (?) with no Preamble; may start with a Shadow Group --
646    // FIXME : We cannot be sure the preable is only zeroes..
647    //         (see ACUSON-24-YBR_FULL-RLE.dcm )
648    if ( 
649        zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
650        zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
651        zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
652        zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 ||
653        zero == 0x0028 || 0x2800    // worse : some ACR-NEMA like files 
654                                    // start 00028 group ?!?      
655        )
656    {
657       std::string msg = Util::Format(
658         "ACR/DICOM starting by 0x(%04x) at the beginning of the file\n", zero);
659       // FIXME : is it a Warning message, or a Debug message?
660       gdcmWarningMacro( msg.c_str() );
661       return Fp;
662    }
663    
664    // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
665    CloseFile();
666    // Don't user Warning nor Error, not to pollute the output
667    // while directory recursive parsing ...
668    gdcmDebugMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
669                       << Filename.c_str()); 
670    return 0;
671 }
672
673 /**
674  * \brief closes the file  
675  * @return  TRUE if the close was successfull 
676  */
677 bool Document::CloseFile()
678 {
679    if ( Fp )
680    {
681       Fp->close();
682       delete Fp;
683       Fp = 0;
684    }
685    return true;
686 }
687
688 /**
689  * \brief Writes in a file all the Entries (Dicom Elements) 
690  * @param fp file pointer on an already open file (actually: Output File Stream)
691  * @param filetype Type of the File to be written 
692  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
693  */
694 void Document::WriteContent(std::ofstream *fp, FileType filetype)
695 {
696    // Skip if user wants to write an ACR-NEMA file
697
698    if ( filetype == ImplicitVR || filetype == ExplicitVR ||
699         filetype == JPEG || filetype == JPEG2000 )
700    {
701       // writing Dicom File Preamble
702       char filePreamble[128];
703       memset(filePreamble, 0, 128);
704       fp->write(filePreamble, 128);
705       fp->write("DICM", 4);
706    }
707    /*
708     * \todo rewrite later, if really usefull
709     *       - 'Group Length' element is optional in DICOM
710     *       - but un-updated odd groups lengthes can causes pb
711     *         (xmedcon breaker)
712     *
713     * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
714     *    UpdateGroupLength(false,filetype);
715     * if ( filetype == ACR)
716     *    UpdateGroupLength(true,ACR);
717     *
718     * --> Computing group length for groups with embeded Sequences
719     * --> was too much tricky / we were [in a hurry / too lazy]
720     * --> We don't write the element 0x0000 (group length)
721     */
722
723    ElementSet::WriteContent(fp, filetype); // This one is recursive
724 }
725
726 // -----------------------------------------
727 // Content entries 
728 /**
729  * \brief Loads (from disk) the element content 
730  *        when a string is not suitable
731  * @param group   group number of the Entry 
732  * @param elem  element number of the Entry
733  */
734 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
735 {
736    // Search the corresponding DocEntry
737    DocEntry *docEntry = GetDocEntry(group, elem);
738    if ( !docEntry )
739    {
740       gdcmDebugMacro(std::hex << group << "|" << elem 
741                        <<  " doesn't exist" );
742       return;
743    }
744    DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
745    if ( !dataEntry )
746    {
747       gdcmWarningMacro(std::hex << group << "|" << elem 
748                        <<  " is NOT a DataEntry");
749       return;
750    }
751    LoadEntryBinArea(dataEntry);
752 }
753
754 /**
755  * \brief Loads (from disk) the element content 
756  *        when a string is not suitable
757  * @param entry  Entry whose binArea is going to be loaded
758  */
759 void Document::LoadEntryBinArea(DataEntry *entry) 
760
761    if( entry->GetBinArea() )
762       return;
763
764    bool openFile = !Fp;
765    if ( openFile )
766       OpenFile();
767
768    //size_t o =(size_t)entry->GetOffset();
769    Fp->seekg((size_t)entry->GetOffset(), std::ios::beg);  // FIXME : for each DataEntry !
770
771    size_t l = entry->GetLength();
772    uint8_t *data = new uint8_t[l];
773    if ( !data )
774    {
775       gdcmWarningMacro(  "Cannot allocate DataEntry content for : "
776                        << std::hex << entry->GetGroup() 
777                        << "|" << entry->GetElement() );
778       return;
779    }
780
781    // Read the data
782    Fp->read((char*)data, l);
783    if ( Fp->fail() || Fp->eof() )
784    {
785       delete[] data;
786       entry->SetState(DataEntry::STATE_UNREAD);
787       return;
788    }
789
790    // Swap the data content if necessary
791    uint32_t i;
792    unsigned short vrLgth = 
793                         Global::GetVR()->GetAtomicElementLength(entry->GetVR());
794
795 // FIXME : trouble expected if we read an ... OW Entry (LUT, etc ..)
796 //   if( entry->GetVR() == "OW" )
797 //      vrLgth = 1;
798
799    switch(vrLgth)
800    {
801       case 1:
802       {
803          break;
804       }     
805       case 2:
806       {
807          uint16_t *data16 = (uint16_t *)data;
808          for(i=0;i<l/vrLgth;i++)
809             data16[i] = SwapShort(data16[i]);
810          break;
811       }
812       case 4:
813       {
814          uint32_t *data32 = (uint32_t *)data;
815          for(i=0;i<l/vrLgth;i++)
816             data32[i] = SwapLong(data32[i]);
817          break;
818       }
819       case 8:
820       {
821          double *data64 = (double *)data;
822          for(i=0;i<l/vrLgth;i++)
823             data64[i] = SwapDouble(data64[i]);
824          break;
825       }
826    }
827    
828    entry->SetBinArea(data);
829
830    if ( openFile ) // The file is left in the state (open/close) it was at entrance
831       CloseFile();
832 }
833
834 /**
835  * \brief  Loads the element while preserving the current
836  *         underlying file position indicator as opposed to
837  *        LoadDocEntry that modifies it
838  * \note seems to be unused!.
839  * @param entry   DocEntry whose value will be loaded. 
840  */
841 //void Document::LoadDocEntrySafe(DocEntry *entry)
842 //{
843 //   if ( Fp )
844 //   {
845 //      long PositionOnEntry = Fp->tellg();        // LoadDocEntrySafe is not used
846 //      LoadDocEntry(entry);
847 //      Fp->seekg(PositionOnEntry, std::ios::beg); // LoadDocEntrySafe is not used
848 //   }
849 //}
850
851 /**
852  * \brief   Compares two documents, according to \ref DicomDir rules
853  * \warning Does NOT work with ACR-NEMA files
854  * \todo    Find a trick to solve the pb (use RET fields ?)
855  * @param   document to compare with current one
856  * @return  true if 'smaller'
857  */
858 bool Document::operator<(Document &document)
859 {
860    // Patient Name
861    std::string s1 = GetEntryString(0x0010,0x0010);
862    std::string s2 = document.GetEntryString(0x0010,0x0010);
863    if (s1 < s2)
864    {
865       return true;
866    }
867    else if ( s1 > s2 )
868    {
869       return false;
870    }
871    else
872    {
873       // Patient ID
874       s1 = GetEntryString(0x0010,0x0020);
875       s2 = document.GetEntryString(0x0010,0x0020);
876       if ( s1 < s2 )
877       {
878          return true;
879       }
880       else if ( s1 > s2 )
881       {
882          return false;
883       }
884       else
885       {
886          // Study Instance UID
887          s1 = GetEntryString(0x0020,0x000d);
888          s2 = document.GetEntryString(0x0020,0x000d);
889          if ( s1 < s2 )
890          {
891             return true;
892          }
893          else if ( s1 > s2 )
894          {
895             return false;
896          }
897          else
898          {
899             // Serie Instance UID
900             s1 = GetEntryString(0x0020,0x000e);
901             s2 = document.GetEntryString(0x0020,0x000e);    
902             if ( s1 < s2 )
903             {
904                return true;
905             }
906             else if ( s1 > s2 )
907             {
908                return false;
909             }
910          }
911       }
912    }
913    return false;
914 }
915
916 //-----------------------------------------------------------------------------
917 // Protected
918
919 /**
920  * \brief Reads a given length of bytes
921  *       (in order to avoid to many CPU time consuming fread-s)
922  * @param l length to read 
923  */
924 void Document::ReadBegBuffer(size_t l)
925    throw( FormatError )
926 {   
927    Fp->read (BegBuffer, (size_t)l);
928    if ( Fp->fail() )
929    {
930       throw FormatError( "Document::ReadBegBuffer()", " file error." );
931    }
932    if ( Fp->eof() )
933    {
934       throw FormatError( "Document::ReadBegBuffer()", "EOF." );
935    }
936    PtrBegBuffer = BegBuffer;
937    CurrentOffsetPosition+=l;
938 }
939 /**
940  * \brief Reads a supposed to be 16 Bits integer
941  *       (swaps it depending on processor endianness) 
942  * @return read value
943  */
944 uint16_t Document::ReadInt16()
945    throw( FormatError )
946 {
947    uint16_t g;
948    Fp->read ((char*)&g, (size_t)2);
949    if ( Fp->fail() )
950    {
951       throw FormatError( "Document::ReadInt16()", " file error." );
952    }
953    if ( Fp->eof() )
954    {
955       throw FormatError( "Document::ReadInt16()", "EOF." );
956    }
957    g = SwapShort(g); 
958    return g;
959 }
960
961 /**
962  * \brief Gets from BegBuffer a supposed to be 16 Bits integer
963  *       (swaps it depending on processor endianness) 
964  * @return read value
965  */
966 uint16_t Document::GetInt16()
967 {
968    uint16_t g = *((uint16_t*)PtrBegBuffer);
969    g = SwapShort(g);
970    PtrBegBuffer+=2; 
971    return g;
972 }
973 /**
974  * \brief  Reads a supposed to be 32 Bits integer
975  *        (swaps it depending on processor endianness)  
976  * @return read value
977  */
978 uint32_t Document::ReadInt32()
979    throw( FormatError )
980 {
981    uint32_t g;
982    Fp->read ((char*)&g, (size_t)4);
983    if ( Fp->fail() )
984    {
985       throw FormatError( "Document::ReadInt32()", " file error." );
986    }
987    if ( Fp->eof() )
988    {
989       throw FormatError( "Document::ReadInt32()", "EOF." );
990    }
991    g = SwapLong(g);
992    return g;
993 }
994
995 /**
996  * \brief Gets from BegBuffer a supposed to be 32 Bits integer
997  *       (swaps it depending on processor endianness) 
998  * @return read value
999  */
1000 uint32_t Document::GetInt32()
1001 {
1002    uint32_t g = *((uint32_t*)PtrBegBuffer);
1003    g = SwapLong(g); 
1004    PtrBegBuffer+=4;
1005    return g;
1006 }
1007
1008 /**
1009  * \brief   Re-computes the length of the Dicom group 0002.
1010  */
1011 int Document::ComputeGroup0002Length( ) 
1012 {
1013    uint16_t gr;
1014    VRKey vr;
1015    
1016    int groupLength = 0;
1017    bool found0002 = false;   
1018   
1019    // for each zero-level Tag in the DCM Header
1020    DocEntry *entry = GetFirstEntry();
1021    while( entry )
1022    {
1023       gr = entry->GetGroup();
1024
1025       if ( gr == 0x0002 )
1026       {
1027          found0002 = true;
1028
1029          if ( entry->GetElement() != 0x0000 )
1030          {
1031             vr = entry->GetVR();
1032
1033             //if ( (vr == "OB")||(vr == "OW")||(vr == "UT")||(vr == "SQ"))
1034             // (no SQ, OW, UT in group 0x0002;)
1035                if ( vr == "OB" ) 
1036                {
1037                   // explicit VR AND (OB, OW, SQ, UT) : 4 more bytes
1038                   groupLength +=  4;
1039                }
1040             groupLength += 2 + 2 + 4 + entry->GetLength();   
1041          }
1042       }
1043       else if (found0002 )
1044          break;
1045
1046       entry = GetNextEntry();
1047    }
1048    return groupLength; 
1049 }
1050
1051 /**
1052  * \brief   CallStartMethod
1053  */
1054 void Document::CallStartMethod()
1055 {
1056    Progress = 0.0f;
1057    Abort    = false;
1058    CommandManager::ExecuteCommand(this,CMD_STARTPROGRESS);
1059 }
1060
1061 /**
1062  * \brief   CallProgressMethod
1063  */
1064 void Document::CallProgressMethod()
1065 {
1066    CommandManager::ExecuteCommand(this,CMD_PROGRESS);
1067 }
1068
1069 /**
1070  * \brief   CallEndMethod
1071  */
1072 void Document::CallEndMethod()
1073 {
1074    Progress = 1.0f;
1075    CommandManager::ExecuteCommand(this,CMD_ENDPROGRESS);
1076 }
1077
1078 //-----------------------------------------------------------------------------
1079 // Private
1080 /**
1081  * \brief Loads all the needed Dictionaries
1082  * \warning NOT end user intended method !
1083  */
1084 void Document::Initialize() 
1085 {
1086    RefPubDict = Global::GetDicts()->GetDefaultPubDict();
1087    RefShaDict = NULL;
1088    Filetype   = Unknown;
1089 }
1090
1091 /**
1092  * \brief   Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1093  * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
1094  * @param offset start of parsing
1095  * @param l_max  length to parse (meaningless when we are in 'delimitor mode')
1096  * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
1097  */ 
1098 void Document::ParseDES(DocEntrySet *set, long offset, 
1099                         long l_max, bool delim_mode)
1100 {
1101    DocEntry *newDocEntry;
1102    DataEntry *newDataEntry;
1103    SeqEntry *newSeqEntry;
1104    //VRKey vr;
1105    bool used; // will be set to false when something wrong happens to an Entry.
1106               // (Entry will then be deleted)
1107    bool delim_mode_intern = delim_mode;
1108    bool first = true;
1109    gdcmDebugMacro( "Enter in ParseDES, delim-mode " <<  delim_mode
1110                      << " at offset " << std::hex << "0x(" << offset << ")" );    
1111    while (true)
1112    {
1113    
1114    ///\todo FIXME : On 64 bits processors, tellg gives unexpected results after a while ?
1115    ///              Probabely a bug in gdcm code somwhere (some memory erased ?)
1116
1117 // Uncomment to track the bug
1118 /*   
1119    if( Debug::GetDebugFlag() )   
1120       std::cout << std::dec <<"(long)(Fp->tellg()) " << (long)(Fp->tellg()) // in Debug mode
1121                 << std::hex << " 0x(" <<(long)(Fp->tellg()) <<  ")" << std::endl;
1122  */ 
1123  
1124    // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry   
1125       if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1126          if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per DocEntry, when no delim mode
1127          {
1128             break;
1129          }
1130
1131       newDocEntry = ReadNextDocEntry( );
1132
1133       if ( !newDocEntry )
1134       {
1135          break;
1136       }
1137       
1138       // Uncoment this cerr line to be able to 'follow' the DocEntries
1139       // when something *very* strange happens
1140       if( Debug::GetDebugFlag() ) 
1141          std::cerr<<newDocEntry->GetKey()<<" "<<newDocEntry->GetVR()<<std::endl;
1142
1143        // an Item Starter found elsewhere but in the first position
1144        // of a SeqEntry means previous entry was a Sequence
1145        // but we didn't get it (private Sequence + Implicit VR)
1146        // we have to backtrack.
1147       if ( !first && newDocEntry->IsItemStarter() )
1148       {
1149          // Debug message within the method !
1150          newDocEntry = Backtrack(newDocEntry);
1151       }
1152       else
1153       { 
1154          PreviousDocEntry = newDocEntry; 
1155       }
1156  
1157       used = true;
1158       newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1159
1160       if ( newDataEntry )  
1161       {
1162          //////////////////////////// DataEntry
1163  
1164          //vr = newDocEntry->GetVR(); // useless ?
1165
1166          if ( !set->AddEntry( newDataEntry ) )
1167          {
1168             gdcmDebugMacro( "in ParseDES : cannot add a DataEntry "
1169                                  << newDataEntry->GetKey()
1170                                  << " (at offset : 0x(" 
1171                                  << newDataEntry->GetOffset() << ") )" );
1172             used=false;
1173          }
1174          else
1175          {
1176             newDataEntry->Delete();
1177             // Load only if we can add (not a duplicate key)
1178             LoadDocEntry( newDataEntry );
1179          }
1180          if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1181          {
1182             if ( newDataEntry->GetGroup()%2 != 0 )   // if Shadow Group
1183             {
1184                if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1185                {
1186                   std::string strLgrGroup = newDataEntry->GetString();
1187
1188                   int lgrGroup;
1189                   //if ( newDataEntry->IsUnfound() ) /?!? JPR
1190                   {
1191                      lgrGroup = atoi(strLgrGroup.c_str());
1192                      Fp->seekg(lgrGroup, std::ios::cur); // Once per Shadow group, when NOSHADOW
1193                      RemoveEntry( newDocEntry );  // Remove and delete
1194                      continue;
1195                   }
1196                }
1197             }
1198          }
1199
1200          bool delimitor = newDataEntry->IsItemDelimitor(); 
1201          bool outOfBounds = false;
1202          if (!delim_mode )
1203             if ( ((long)(Fp->tellg())-offset) >= l_max ) //Once per DataEntry when no delim mode
1204                outOfBounds = true;
1205
1206   //       'and then', 'or else' don't exist in C++ :-(
1207   //       if ( (delimitor) || 
1208   //             (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) ) // Once per DataEntry
1209
1210          if ( delimitor || outOfBounds )
1211          {
1212             if ( !used )
1213                newDocEntry->Delete();
1214             break;
1215          }
1216
1217          // Just to make sure we are at the beginning of next entry.
1218          SkipToNextDocEntry(newDocEntry); // FIXME : once per DocEntry, segfault if commented out
1219       }
1220       else
1221       {
1222          /////////////////////// SeqEntry :  VR = "SQ"
1223
1224          unsigned long l = newDocEntry->GetReadLength();          
1225          if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1226          {
1227             if ( l == 0xffffffff )
1228             {
1229               delim_mode_intern = true;
1230             }
1231             else
1232             {
1233               delim_mode_intern = false;
1234             }
1235          }
1236
1237          if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1238          { 
1239            // User asked to skip SeQuences *only* if they belong to Shadow Group
1240             if ( newDocEntry->GetGroup()%2 != 0 )
1241             {
1242                 Fp->seekg( l, std::ios::cur);  // once per SQITEM, when NOSHADOWSEQ
1243                 newDocEntry->Delete();  // Delete, not in the set 
1244                 continue;  
1245             } 
1246          } 
1247          if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern ) 
1248          {
1249            // User asked to skip *any* SeQuence
1250             Fp->seekg( l, std::ios::cur); // Once per SQ, when NOSEQ
1251             newDocEntry->Delete(); // Delete, not in the set
1252             continue;
1253          }
1254          // delay the dynamic cast as late as possible
1255          newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1256          
1257          // no other way to create the Delimitor ...
1258          newSeqEntry->SetDelimitorMode( delim_mode_intern );
1259
1260          // At the top of the hierarchy, stands a Document. When "set"
1261          // is a Document, then we are building the first depth level.
1262          // Hence the SeqEntry we are building simply has a depth
1263          // level of one:
1264         if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1265          {
1266             newSeqEntry->SetDepthLevel( 1 );
1267          }
1268          // But when "set" is already a SQItem, we are building a nested
1269          // sequence, and hence the depth level of the new SeqEntry
1270          // we are building, is one level deeper:
1271
1272          // time waste hunting
1273          else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1274          {
1275             newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1276          }
1277
1278          if ( l != 0 )
1279          {  // Don't try to parse zero-length sequences
1280
1281             gdcmDebugMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1282                                << " at offset 0x(" << std::hex
1283                                << newDocEntry->GetOffset() << ")");
1284
1285             ParseSQ( newSeqEntry, 
1286                      newDocEntry->GetOffset(),
1287                      l, delim_mode_intern);
1288
1289             gdcmDebugMacro( "Exit from ParseSQ, delim " << delim_mode_intern);
1290          }
1291          if ( !set->AddEntry( newSeqEntry ) )
1292          {
1293             gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1294                                 << newSeqEntry->GetKey()
1295                                 << " (at offset : 0x(" 
1296                                 << newSeqEntry->GetOffset() << ") )" ); 
1297             used = false;
1298          }
1299          else
1300          {
1301             newDocEntry->Delete();
1302          }
1303
1304       // if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry
1305  
1306          if ( !delim_mode ) // 'and then' doesn't exist in C++ :-(
1307             if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SeqEntry when no delim mode
1308      
1309          {
1310             if ( !used )
1311                newDocEntry->Delete();
1312             break;
1313          }
1314       }  // end SeqEntry : VR = "SQ"
1315
1316       if ( !used )
1317       {
1318          newDocEntry->Delete();
1319       }
1320       first = false;
1321    }                               // end While
1322    gdcmDebugMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1323 }
1324
1325 /**
1326  * \brief   Parses a Sequence ( SeqEntry after SeqEntry)
1327  * @return  parsed length for this level
1328  */ 
1329 void Document::ParseSQ( SeqEntry *seqEntry,
1330                         long offset, long l_max, bool delim_mode)
1331 {
1332    int SQItemNumber = 0;
1333    bool dlm_mod;
1334    long offsetStartCurrentSQItem = offset;
1335
1336    while (true)
1337    {
1338       // the first time, we read the fff0,e000 of the first SQItem
1339       DocEntry *newDocEntry = ReadNextDocEntry();
1340
1341       if ( !newDocEntry )
1342       {
1343          gdcmWarningMacro("in ParseSQ : should never get here!");
1344          break;
1345       }
1346       if ( delim_mode )
1347       {
1348          if ( newDocEntry->IsSequenceDelimitor() )
1349          {
1350             seqEntry->SetDelimitationItem( newDocEntry ); 
1351             newDocEntry->Delete();
1352             break;
1353          }
1354       }
1355       else // ! delim_mode
1356       {
1357          if ( ((long)(Fp->tellg())-offset) >= l_max) // Once per SQItem when no delim mode
1358          {
1359             newDocEntry->Delete();
1360             break;
1361          }
1362       }
1363       // create the current SQItem
1364       SQItem *itemSQ = SQItem::New( seqEntry->GetDepthLevel() );
1365       unsigned int l = newDocEntry->GetReadLength();
1366       
1367       if ( l == 0xffffffff )
1368       {
1369          dlm_mod = true;
1370       }
1371       else
1372       {
1373          dlm_mod = false;
1374       }
1375             
1376       // fill up the current SQItem, starting at the beginning of fff0,e000
1377       
1378       Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);        // Once per SQItem
1379       ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1380       offsetStartCurrentSQItem = Fp->tellg();                    // Once per SQItem
1381  
1382       seqEntry->AddSQItem( itemSQ, SQItemNumber ); 
1383       itemSQ->Delete();
1384       newDocEntry->Delete();
1385       SQItemNumber++;
1386       //if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max ) //JPRx
1387       if ( !delim_mode && (offsetStartCurrentSQItem-offset ) >= l_max )
1388       {
1389          break;
1390       }
1391    }
1392 }
1393
1394 /**
1395  * \brief   When a private Sequence + Implicit VR is encountered
1396  *           we cannot guess it's a Sequence till we find the first
1397  *           Item Starter. We then backtrack to do the job.
1398  * @param   docEntry Item Starter that warned us 
1399  */
1400 DocEntry *Document::Backtrack(DocEntry *docEntry)
1401 {
1402    // delete the Item Starter, built erroneously out of any Sequence
1403    // it's not yet in the HTable/chained list
1404    docEntry->Delete();
1405
1406    // Get all info we can from PreviousDocEntry
1407    uint16_t group = PreviousDocEntry->GetGroup();
1408    uint16_t elem  = PreviousDocEntry->GetElement();
1409    uint32_t lgt   = PreviousDocEntry->GetLength();
1410    long offset    = PreviousDocEntry->GetOffset();
1411
1412    gdcmDebugMacro( "Backtrack :" << std::hex << group 
1413                                  << "|" << elem
1414                                  << " at offset 0x(" <<offset << ")" );
1415    RemoveEntry( PreviousDocEntry );
1416
1417    // forge the Seq Entry
1418    DocEntry *newEntry = NewSeqEntry(group, elem);
1419    newEntry->SetLength(lgt);
1420    newEntry->SetOffset(offset);
1421
1422    // Move back to the beginning of the Sequence
1423
1424    Fp->seekg(offset, std::ios::beg); // Only for Shadow Implicit VR SQ
1425    return newEntry;
1426 }
1427
1428 /**
1429  * \brief   Loads (or not) the element content depending if its length exceeds
1430  *          or not the value specified with Document::SetMaxSizeLoadEntry()
1431  * @param   entry Header Entry (Dicom Element) to be dealt with
1432  * @param forceLoad whether you want to force loading of 'long' elements
1433  */
1434 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1435 {
1436    uint16_t group   = entry->GetGroup();
1437    uint16_t elem    = entry->GetElement();
1438    const VRKey  &vr = entry->GetVR();
1439    uint32_t length  = entry->GetLength();
1440
1441  //  Fp->seekg((long)entry->GetOffset(), std::ios::beg); // JPRx
1442
1443    // A SeQuence "contains" a set of Elements.  
1444    //          (fffe e000) tells us an Element is beginning
1445    //          (fffe e00d) tells us an Element just ended
1446    //          (fffe e0dd) tells us the current SeQuence just ended
1447    //          (fffe 0000) is an 'impossible' tag value, 
1448    //                                    found in MR-PHILIPS-16-Multi-Seq.dcm
1449    
1450    if ( (group == 0xfffe && elem != 0x0000 ) || vr == "SQ" )
1451    {
1452       // NO more value field for SQ !
1453       return;
1454    }
1455
1456    DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1457    if( !dataEntryPtr )
1458    {
1459       return;
1460    }
1461
1462    // When the length is zero things are easy:
1463    if ( length == 0 )
1464    {
1465       dataEntryPtr->SetBinArea(NULL,true);
1466       return;
1467    }
1468
1469    // The elements whose length is bigger than the specified upper bound
1470    // are not loaded.
1471
1472    if (!forceLoad)
1473    {
1474       if (length > MaxSizeLoadEntry)
1475       {
1476          dataEntryPtr->SetBinArea(NULL,true);
1477          dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1478
1479        // to be sure we are at the end of the value ...
1480        //  Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1481        //           std::ios::beg);  //JPRx
1482          return;
1483       }
1484    }
1485    
1486    /// \todo: a method that *doesn't* load anything (maybe with MaxSizeLoadEntry=0 ?)
1487    ///       + a ForceLoad call on the +/- 20 'usefull' fields  
1488    ///       Allow user to tell the fields he wants to ForceLoad 
1489    ///       during initial stage.
1490    ///       Later, a GetString or GetBinArea will load the value from disk, if not loaded
1491    ///       + a method that load *everything* that's not yet loaded
1492    
1493    LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1494 }
1495
1496 /**
1497  * \brief  Find the value Length of the passed Doc Entry
1498  * @param  entry Header Entry whose length of the value shall be loaded. 
1499  */
1500 void Document::FindDocEntryLength( DocEntry *entry )
1501    throw ( FormatError )
1502 {
1503    const VRKey &vr  = entry->GetVR();
1504    uint16_t length16;       
1505    
1506    if ( Filetype == ExplicitVR && !entry->IsImplicitVR() ) 
1507    {
1508       if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT" 
1509                                                            || vr == "UN" )
1510       {
1511          // The following reserved two bytes (see PS 3.5-2003, section
1512          // "7.1.2 Data element structure with explicit vr", p 27) must be
1513          // skipped before proceeding on reading the length on 4 bytes.
1514
1515          //Fp->seekg( 2L, std::ios::cur); // Once per OW,OB,SQ DocEntry
1516          uint32_t length32 = ReadInt32(); // Once per OW,OB,SQ DocEntry
1517          CurrentOffsetPosition+=4;
1518          if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff ) 
1519          {
1520             uint32_t lengthOB;
1521             try 
1522             {
1523                lengthOB = FindDocEntryLengthOBOrOW();// for encapsulation of encoded pixel 
1524             }
1525             catch ( FormatUnexpected )
1526             {
1527                // Computing the length failed (this happens with broken
1528                // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1529                // chance to get the pixels by deciding the element goes
1530                // until the end of the file. Hence we artificially fix the
1531                // the length and proceed.
1532                gdcmWarningMacro( " Computing the length failed for " << 
1533                                    entry->GetKey() <<" in " <<GetFileName());
1534
1535                long currentPosition = Fp->tellg(); // Only for gdcm-JPEG-LossLess3a.dcm-like
1536                Fp->seekg(0L,std::ios::end);        // Only for gdcm-JPEG-LossLess3a.dcm-like
1537
1538                long lengthUntilEOF = (long)(Fp->tellg())-currentPosition; // Only for gdcm-JPEG-LossLess3a.dcm-like
1539                Fp->seekg(currentPosition, std::ios::beg);                 // Only for gdcm-JPEG-LossLess3a.dcm-like
1540
1541                entry->SetReadLength(lengthUntilEOF);
1542                entry->SetLength(lengthUntilEOF);
1543                return;
1544             }
1545             entry->SetReadLength(lengthOB);
1546             entry->SetLength(lengthOB);
1547             return;
1548          }
1549          FixDocEntryFoundLength(entry, length32); 
1550          return;
1551       }
1552
1553       // Length is encoded on 2 bytes.
1554       //length16 = ReadInt16();
1555       length16 = GetInt16();
1556
1557       // 0xffff means that we deal with 'No Length' Sequence 
1558       //        or 'No Length' SQItem
1559       if ( length16 == 0xffff) 
1560       {           
1561          length16 = 0;
1562       }
1563       FixDocEntryFoundLength( entry, (uint32_t)length16 );
1564       return;
1565    }
1566    else
1567    {
1568       // Either implicit VR or a non DICOM conformal (see note below) explicit
1569       // VR that ommited the VR of (at least) this element. Farts happen.
1570       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1571       // on Data elements "Implicit and Explicit VR Data Elements shall
1572       // not coexist in a Data Set and Data Sets nested within it".]
1573       // Length is on 4 bytes.
1574
1575      // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1576      // even if Transfer Syntax is 'Implicit VR ...'
1577      // --> Except for 'Implicit VR Big Endian Transfer Syntax GE Private' 
1578      //     where Group 0x0002 is *also* encoded in Implicit VR !
1579
1580       FixDocEntryFoundLength( entry, GetInt32() /*ReadInt32()*/ );
1581       return;
1582    }
1583 }
1584
1585 /**
1586  * \brief  Find the Length till the next sequence delimiter
1587  * \warning NOT end user intended method !
1588  * @return 
1589  */
1590 uint32_t Document::FindDocEntryLengthOBOrOW()
1591    throw( FormatUnexpected )
1592 {
1593    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1594    
1595    long positionOnEntry = Fp->tellg(); // Only for OB,OW DataElements
1596
1597    bool foundSequenceDelimiter = false;
1598    uint32_t totalLength = 0;
1599
1600    while ( !foundSequenceDelimiter )
1601    {
1602       uint16_t group;
1603       uint16_t elem;
1604
1605       try
1606       {
1607          //group = ReadInt16(); // Once per fragment (if any) of OB,OW DataElements
1608          //elem  = ReadInt16(); // Once per fragment (if any) of OB,OW DataElements 
1609          ReadBegBuffer(4); // Once per fragment (if any) of OB,OW DataElements
1610       }
1611       catch ( FormatError )
1612       {
1613          throw FormatError("Unexpected end of file encountered during ",
1614                            "Document::FindDocEntryLengthOBOrOW()");
1615       }
1616       group = GetInt16();
1617       elem  = GetInt16();
1618
1619       // We have to decount the group and element we just read
1620       totalLength += 4;     
1621       if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1622       {
1623          gdcmWarningMacro( 
1624               "Neither an Item tag nor a Sequence delimiter tag on :" 
1625            << std::hex << group << " , " << elem 
1626            << ")" );
1627   
1628          Fp->seekg(positionOnEntry, std::ios::beg); // Once per fragment (if any) of OB,OW DataElements
1629          throw FormatUnexpected( 
1630                "Neither an Item tag nor a Sequence delimiter tag.");
1631       }
1632       if ( elem == 0xe0dd )
1633       {
1634          foundSequenceDelimiter = true;
1635       }
1636       uint32_t itemLength = ReadInt32(); // Once per fragment (if any) of OB,OW DataElements
1637       // We add 4 bytes since we just read the ItemLength with ReadInt32
1638       totalLength += itemLength + 4;
1639       SkipBytes(itemLength);
1640       
1641       if ( foundSequenceDelimiter )
1642       {
1643          break;
1644       }
1645    }
1646    Fp->seekg( positionOnEntry, std::ios::beg); // Only once for OB,OW DataElements
1647    return totalLength;
1648 }
1649
1650 /**
1651  * \brief     Find the Value Representation of the current Dicom Element.
1652  * @return    Value Representation of the current Entry
1653  */
1654 VRKey Document::FindDocEntryVR()
1655 {
1656    if ( Filetype != ExplicitVR )
1657    {
1658       return GDCM_VRUNKNOWN;
1659    }
1660
1661    // Delimiters (0xfffe), are not explicit VR ... 
1662    if ( CurrentGroup == 0xfffe )
1663       return GDCM_VRUNKNOWN;
1664          
1665    //long positionOnEntry;     
1666    //if( Debug::GetWarningFlag() ) 
1667    //  positionOnEntry = Fp->tellg(); // Only in Warning Mode
1668    
1669    // Warning: we believe this is explicit VR (Value Representation) because
1670    // we used a heuristic that found "UL" in the first tag and/or
1671    // 'Transfer Syntax' told us it is.
1672    // Alas this doesn't guarantee that all the tags will be in explicit VR. 
1673    // In some cases one finds implicit VR tags mixed within an explicit VR file
1674    // Well...
1675    // 'Normaly' the only case is : group 0002 Explicit, and other groups Implicit
1676    //
1677    // Hence we make sure the present tag is in explicit VR and try to fix things
1678    // if it happens not to be the case.
1679
1680    VRKey vr;
1681    //Fp->read(&(vr[0]),(size_t)2);
1682    vr[0] = *PtrBegBuffer++;
1683    vr[1] = *PtrBegBuffer++;
1684    
1685    //if ( !CheckDocEntryVR(vr) ) // avoid useless function call
1686    if ( !Global::GetVR()->IsValidVR(vr) )
1687    {
1688 /*   
1689 //      std::cout << "================================================================Unknown VR" 
1690                << std::hex << "0x(" 
1691                         << (unsigned int)vr[0] << "|" << (unsigned int)vr[1] 
1692                         << ")" << "for : " <<  CurrentGroup
1693                         << " at offset : 0x(" << positionOnEntry << ")"
1694                         << std::endl;
1695 */
1696       gdcmWarningMacro( "Unknown VR " << std::hex << "0x(" 
1697                         << (unsigned int)vr[0] << "|" << (unsigned int)vr[1] 
1698                         << ")"  
1699                         << " at offset : 0x(" << CurrentOffsetPosition-4<< ") for group " << CurrentGroup
1700                         );
1701
1702       //Fp->seekg(positionOnEntry, std::ios::beg); //JPRx
1703       //Fp->seekg((long)-2, std::ios::cur);// only for unrecognized VR (?!?) 
1704                                          //see :MR_Philips_Intera_PrivateSequenceExplicitVR.dcm
1705       PtrBegBuffer-=2;
1706       return GDCM_VRUNKNOWN;
1707    }
1708    return vr;
1709 }
1710
1711 /**
1712  * \brief     Check the correspondance between the VR of the header entry
1713  *            and the taken VR. If they are different, the header entry is 
1714  *            updated with the new VR.
1715  * @param     vr    Dicom Value Representation
1716  * @return    false if the VR is incorrect or if the VR isn't referenced
1717  *            otherwise, it returns true
1718 */
1719 bool Document::CheckDocEntryVR(const VRKey &vr)
1720 {
1721    return Global::GetVR()->IsValidVR(vr);
1722 }
1723
1724 /**
1725  * \brief   Skip a given Header Entry 
1726  * @param   entry entry to skip
1727  */
1728 void Document::SkipDocEntry(DocEntry *entry) 
1729 {
1730    SkipBytes(entry->GetLength());
1731 }
1732
1733 /**
1734  * \brief   Skips to the beginning of the next Header Entry 
1735  * @param   currentDocEntry entry to skip
1736  */
1737 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry) 
1738 {
1739    long l = currentDocEntry->GetReadLength();
1740    if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1741                   // ... but PMS imagers happen !
1742       return;
1743    Fp->seekg((size_t)(currentDocEntry->GetOffset()), std::ios::beg); //FIXME :each DocEntry
1744    if (currentDocEntry->GetGroup() != 0xfffe)  // for fffe pb
1745    {
1746       Fp->seekg( l,std::ios::cur);                                 //FIXME :each DocEntry
1747    }
1748 }
1749
1750 /**
1751  * \brief   When the length of an element value is obviously wrong (because
1752  *          the parser went Jabberwocky) one can hope improving things by
1753  *          applying some heuristics.
1754  * @param   entry entry to check
1755  * @param   foundLength first assumption about length (before bug fix, or set to zero if =0xffffffff)    
1756  */
1757 void Document::FixDocEntryFoundLength(DocEntry *entry,
1758                                       uint32_t foundLength)
1759 {
1760    entry->SetReadLength( foundLength );// will be updated only if a bug is found
1761    
1762    if ( foundLength == 0xffffffff)
1763    {
1764       //foundLength = 0;
1765       //entry->SetLength(foundLength);
1766       entry->SetLength(0);
1767       return;  // return ASAP; don't waist time on useless tests
1768    }
1769       
1770    uint16_t gr   = entry->GetGroup();
1771    uint16_t elem = entry->GetElement(); 
1772      
1773    if ( foundLength % 2)
1774    {
1775       gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1776         <<  " in x(" << std::hex << gr << "," << elem <<")");
1777    }
1778       
1779    //////// Fix for some naughty General Electric images.
1780    // Allthough not recent many such GE corrupted images are still present
1781    // on Creatis hard disks. Hence this fix shall remain when such images
1782    // are no longer in use (we are talking a few years, here)...
1783    // Note: XMedCon probably uses such a trick since it is able to read
1784    //       those pesky GE images ...
1785    if ( foundLength == 13)
1786    {
1787       // Only happens for this length !
1788       if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1789       {
1790          foundLength = 10;
1791          entry->SetReadLength(10); // a bug is to be fixed !?
1792       }
1793    }
1794
1795    //////// Fix for some brain-dead 'Leonardo' Siemens images.
1796    // Occurence of such images is quite low (unless one leaves close to a
1797    // 'Leonardo' source. Hence, one might consider commenting out the
1798    // following fix on efficiency reasons.
1799    else if ( gr == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1800    { 
1801    // Ideally we should check we are in Explicit and double check
1802    // that VR=UL... this is done properly in gdcm2
1803       if( foundLength == 6 )
1804       {
1805          gdcmWarningMacro( "Replacing Length from 6 into 4" );
1806          foundLength = 4;
1807          entry->SetReadLength(4); // a bug is to be fixed !
1808       } 
1809       else if ( foundLength%4 )
1810       {
1811         gdcmErrorMacro( "This looks like to a buggy Siemens DICOM file."
1812         "The length of this tag seems to be wrong" );
1813       }
1814    }
1815
1816    else if ( entry->GetVR() == "SQ" )
1817    {
1818       foundLength = 0;      // ReadLength is unchanged
1819    }
1820
1821    //////// We encountered a 'delimiter' element i.e. a tag of the form
1822    // "fffe|xxxx" which is just a marker. Delimiters length should not be
1823    // taken into account.
1824    else if ( gr == 0xfffe )
1825    {
1826      // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1827      // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1828      // causes extra troubles...
1829      if ( elem != 0x0000 )
1830      {
1831         foundLength = 0;
1832      }
1833      else
1834      {
1835         foundLength=12; // to skip the mess that follows this bugged Tag !
1836      }
1837    }
1838    entry->SetLength(foundLength);
1839 }
1840
1841 /**
1842  * \brief   Apply some heuristics to predict whether the considered 
1843  *          element value contains/represents an integer or not.
1844  * @param   entry The element value on which to apply the predicate.
1845  * @return  The result of the heuristical predicate.
1846  */
1847 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1848 {
1849    uint16_t elem         = entry->GetElement();
1850    uint16_t group        = entry->GetGroup();
1851    const VRKey &vr       = entry->GetVR();
1852    uint32_t length       = entry->GetLength();
1853
1854    // When we have some semantics on the element we just read, and if we
1855    // a priori know we are dealing with an integer, then we shall be
1856    // able to swap its element value properly.
1857    if ( elem == 0 )  // This is the group length of the group
1858    {  
1859       if ( length == 4 )
1860       {
1861          return true;
1862       }
1863       else 
1864       {
1865          // Although this should never happen, still some images have a
1866          // corrupted group length [e.g. have a glance at offset x(8336) of
1867          // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1868          // Since for dicom compliant and well behaved headers, the present
1869          // test is useless (and might even look a bit paranoid), when we
1870          // encounter such an ill-formed image, we simply display a warning
1871          // message and proceed on parsing (while crossing fingers).
1872          long filePosition = Fp->tellg(); // Only when elem 0x0000 length is not 4 (?!?)
1873          (void)filePosition;
1874          gdcmWarningMacro( "Erroneous Group Length element length  on : (" 
1875            << std::hex << group << " , " << elem
1876            << ") -before- position x(" << filePosition << ")"
1877            << "lgt : " << length );
1878       }
1879    }
1880
1881    if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1882    {
1883       return true;
1884    }   
1885    return false;
1886 }
1887
1888 /**
1889  * \brief   Discover what the swap code is (among little endian, big endian,
1890  *          bad little endian, bad big endian).
1891  *          sw is set
1892  * @return false when we are absolutely sure 
1893  *               it's neither ACR-NEMA nor DICOM
1894  *         true  when we hope ours assuptions are OK
1895  */
1896 bool Document::CheckSwap()
1897 {   
1898    uint32_t  s32;
1899    uint16_t  s16;
1900        
1901    char deb[256];
1902     
1903    // First, compare HostByteOrder and NetworkByteOrder in order to
1904    // determine if we shall need to swap bytes (i.e. the Endian type).
1905    bool net2host = Util::IsCurrentProcessorBigEndian();
1906          
1907    // The easiest case is the one of a 'true' DICOM header, we just have
1908    // to look for the string "DICM" inside the file preamble.
1909    Fp->read(deb, 256);
1910    
1911    char *entCur = deb + 128;
1912    if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1913    {
1914       gdcmDebugMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1915       
1916       // Group 0002 should always be VR, and the first element 0000
1917       // Let's be carefull (so many wrong headers ...)
1918       // and determine the value representation (VR) : 
1919       // Let's skip to the first element (0002,0000) and check there if we find
1920       // "UL"  - or "OB" if the 1st one is (0002,0001) -,
1921       // in which case we (almost) know it is explicit VR.
1922       // WARNING: if it happens to be implicit VR then what we will read
1923       // is the length of the group. If this ascii representation of this
1924       // length happens to be "UL" then we shall believe it is explicit VR.
1925       // We need to skip :
1926       // * the 128 bytes of File Preamble (often padded with zeroes),
1927       // * the 4 bytes of "DICM" string,
1928       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1929       // i.e. a total of  136 bytes.
1930       entCur = deb + 136;
1931      
1932       // group 0x0002 *is always* Explicit VR Sometimes,
1933       // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1934       // *Implicit* VR  (see former 'gdcmData/icone.dcm')
1935       
1936       if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1937            memcmp(entCur, "OB", (size_t)2) == 0 ||
1938            memcmp(entCur, "UI", (size_t)2) == 0 ||
1939            memcmp(entCur, "CS", (size_t)2) == 0 )  // CS, to remove later
1940                                                    // when Write DCM *adds*
1941       // FIXME
1942       // Use Document::dicom_vr to test all the possibilities
1943       // instead of just checking for UL, OB and UI !? group 0000 
1944       {
1945          Filetype = ExplicitVR;
1946          gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1947       } 
1948       else 
1949       {
1950          Filetype = ImplicitVR;
1951          gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1952                         << "Looks like a bugged Header!");
1953       }
1954       
1955       // Here, we assume that the file IS kosher Dicom !
1956       // (The meta elements - group 0x0002 - ARE little endian !)
1957       if ( net2host )
1958       {
1959          SwapCode = 4321;
1960          gdcmDebugMacro( "HostByteOrder != NetworkByteOrder, SwapCode = 4321");
1961       }
1962       else 
1963       {
1964          SwapCode = 1234;
1965          gdcmDebugMacro( "HostByteOrder = NetworkByteOrder, SwapCode = 1234");
1966       }
1967       
1968       // Position the file position indicator at first tag 
1969       // (i.e. after the file preamble and the "DICM" string).
1970
1971       Fp->seekg ( 132L, std::ios::beg); // Once per Document
1972       CurrentOffsetPosition = 132;
1973       return true;
1974    } // ------------------------------- End of DicomV3 ----------------
1975
1976    // Alas, this is not a DicomV3 file and whatever happens there is no file
1977    // preamble. We can reset the file position indicator to where the data
1978    // is (i.e. the beginning of the file).
1979
1980    gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1981
1982    Fp->seekg(0, std::ios::beg); // Once per ACR-NEMA Document
1983    CurrentOffsetPosition = 0;
1984    // Let's check 'No Preamble Dicom File' :
1985    // Should start with group 0x0002
1986    // and be Explicit Value Representation
1987
1988    s16 = *((uint16_t *)(deb));
1989    SwapCode = 0;     
1990    switch ( s16 )
1991    {
1992       case 0x0002 :
1993          SwapCode = 1234;
1994          entCur = deb + 4;
1995          break;
1996       case 0x0200 :
1997          SwapCode = 4321;
1998          entCur = deb + 6;
1999     } 
2000
2001    if ( SwapCode != 0 )
2002    {
2003       if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
2004            memcmp(entCur, "OB", (size_t)2) == 0 ||
2005            memcmp(entCur, "UI", (size_t)2) == 0 ||
2006            memcmp(entCur, "SH", (size_t)2) == 0 ||
2007            memcmp(entCur, "AE", (size_t)2) == 0 ||
2008            memcmp(entCur, "OB", (size_t)2) == 0 )
2009          {
2010             Filetype = ExplicitVR;  // FIXME : not enough to say it's Explicit
2011                                     // Wait untill reading Transfer Syntax
2012             gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
2013             return true;
2014           }
2015     }
2016 // ------------------------------- End of 'No Preamble' DicomV3 -------------
2017
2018    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2019    // By clean we mean that the length of the first group is written down.
2020    // If this is the case and since the length of the first group HAS to be
2021    // four (bytes), then determining the proper swap code is straightforward.
2022
2023    entCur = deb + 4;
2024    // We assume the array of char we are considering contains the binary
2025    // representation of a 32 bits integer. Hence the following dirty
2026    // trick :
2027    s32 = *((uint32_t *)(entCur));
2028    switch( s32 )
2029    {
2030       case 0x00040000 :
2031          SwapCode = 3412;
2032          Filetype = ACR;
2033          return true;
2034       case 0x04000000 :
2035          SwapCode = 4321;
2036          Filetype = ACR;
2037          return true;
2038       case 0x00000400 :
2039          SwapCode = 2143;
2040          Filetype = ACR;
2041          return true;
2042       case 0x00000004 :
2043          SwapCode = 1234;
2044          Filetype = ACR;
2045          return true;
2046       default :
2047          // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2048          // It is time for despaired wild guesses. 
2049          // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2050          //  i.e. the 'group length' element is not present :     
2051          
2052          //  check the supposed-to-be 'group number'
2053          //  in ( 0x0001 .. 0x0008 )
2054          //  to determine ' SwapCode' value .
2055          //  Only 0 or 4321 will be possible 
2056          //  (no oportunity to check for the formerly well known
2057          //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
2058          //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc-3, 4, ..., 8-)
2059          //  the file IS NOT ACR-NEMA nor DICOM V3
2060          //  Find a trick to tell it the caller...
2061       
2062          s16 = *((uint16_t *)(deb));
2063  
2064          gdcmDebugMacro("not a DicomV3 nor a 'clean' ACR/NEMA;"
2065                      << " (->despaired wild guesses !)"); 
2066       
2067          switch ( s16 )
2068          {
2069             case 0x0001 :
2070             case 0x0002 :
2071             case 0x0003 :
2072             case 0x0004 :
2073             case 0x0005 :
2074             case 0x0006 :
2075             case 0x0007 :
2076             case 0x0008 :
2077             case 0x0028 :
2078                SwapCode = 1234;
2079                Filetype = ACR;
2080                return true;
2081             case 0x0100 :
2082             case 0x0200 :
2083             case 0x0300 :
2084             case 0x0400 :
2085             case 0x0500 :
2086             case 0x0600 :
2087             case 0x0700 :
2088             case 0x0800 :
2089             case 0x2800 :
2090                SwapCode = 4321;
2091                Filetype = ACR;
2092                return true;
2093             default :
2094                gdcmWarningMacro("ACR/NEMA unfound swap info (Hopeless !)");
2095                Filetype = Unknown;
2096                return false;
2097          }
2098    }
2099 }
2100
2101 /**
2102  * \brief Change the Byte Swap code. 
2103  */
2104 void Document::SwitchByteSwapCode() 
2105 {
2106    gdcmDebugMacro( "Switching Byte Swap code from "<< SwapCode
2107                      << " at: 0x" << std::hex << Fp->tellg() );  // Only when DEBUG
2108    if ( SwapCode == 1234 ) 
2109    {
2110       SwapCode = 4321;
2111    }
2112    else if ( SwapCode == 4321 ) 
2113    {
2114       SwapCode = 1234;
2115    }
2116    else if ( SwapCode == 3412 ) 
2117    {
2118       SwapCode = 2143;
2119    }
2120    else if ( SwapCode == 2143 )
2121    {
2122       SwapCode = 3412;
2123    }
2124    gdcmDebugMacro( " Into: "<< SwapCode );
2125 }
2126
2127 /**
2128  * \brief  during parsing, Header Elements too long are not loaded in memory
2129  * @param newSize new size
2130  */
2131 void Document::SetMaxSizeLoadEntry(long newSize)
2132 {
2133    if ( newSize < 0 )
2134    {
2135       return;
2136    }
2137    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2138    {
2139       MaxSizeLoadEntry = 0xffffffff;
2140       return;
2141    }
2142    MaxSizeLoadEntry = newSize;
2143 }
2144
2145 /**
2146  * \brief   Read the next tag WITHOUT loading it's value
2147  *          (read the 'Group Number', the 'Element Number',
2148  *          gets the Dict Entry
2149  *          gets the VR, gets the length, gets the offset value)
2150  * @return  On succes : the newly created DocEntry, NULL on failure.
2151  */
2152 DocEntry *Document::ReadNextDocEntry()
2153 {
2154    try
2155    {
2156       ReadBegBuffer(8); // Avoid to many time consuming freads
2157       //CurrentGroup = ReadInt16();
2158       //CurrentElem  = ReadInt16();
2159    }
2160    catch ( FormatError )
2161    {
2162       // We reached the EOF (or an error occured) therefore
2163       // header parsing has to be considered as finished.
2164       return 0;
2165    }
2166    
2167    CurrentGroup = GetInt16();
2168    CurrentElem  = GetInt16();
2169    
2170    // In 'true DICOM' files Group 0002 is always little endian
2171    if ( HasDCMPreamble )
2172    {
2173       if ( !Group0002Parsed && CurrentGroup != 0x0002) // avoid calling a function when useless
2174          HandleOutOfGroup0002(CurrentGroup, CurrentElem);
2175       else
2176          // Sometimes file contains groups of tags with reversed endianess.
2177          HandleBrokenEndian(CurrentGroup, CurrentElem);
2178     }
2179
2180    VRKey vr = FindDocEntryVR();
2181    VRKey realVR = vr;
2182
2183    if ( vr == GDCM_VRUNKNOWN )
2184    {
2185       if ( CurrentElem == 0x0000 ) // Group Length
2186       {
2187          realVR = "UL";     // must be UL
2188       }
2189       else if (CurrentGroup == 0xfffe) // Don't get DictEntry for Delimitors
2190       {
2191          realVR = "UL";
2192       }
2193
2194       // Commented out in order not to generate 'Shadow Groups' where some 
2195       // Data Elements are Explicit VR and some other ones Implicit VR
2196       // (Stupid MatLab DICOM Reader couldn't read gdcm-written images)
2197       /*
2198       else if (CurrentGroup%2 == 1 &&  
2199                                (CurrentElem >= 0x0010 && CurrentElem <=0x00ff ))
2200       {  
2201       // DICOM PS 3-5 7.8.1 a) states that those 
2202       // (gggg-0010->00FF where gggg is odd) attributes have to be LO
2203          realVR = "LO";
2204       }
2205       */
2206       else
2207       {
2208          DictEntry *dictEntry = GetDictEntry(CurrentGroup,CurrentElem);//only when ImplicitVR
2209          if ( dictEntry )
2210          {
2211             realVR = dictEntry->GetVR();
2212             dictEntry->Unregister(); // GetDictEntry registered it 
2213          }
2214       }
2215    }
2216
2217    DocEntry *newEntry;
2218    //if ( Global::GetVR()->IsVROfSequence(realVR) )
2219    if (realVR == "SQ")
2220    {
2221       newEntry = NewSeqEntry(CurrentGroup, CurrentElem);
2222    }
2223    else
2224    {
2225       newEntry = NewDataEntry(CurrentGroup, CurrentElem, realVR);
2226       static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
2227    }
2228
2229    if ( vr == GDCM_VRUNKNOWN )
2230    {
2231       if ( Filetype == ExplicitVR )
2232       {
2233          // We thought this was explicit VR, but we end up with an
2234          // implicit VR tag. Let's backtrack.
2235  
2236          //if ( newEntry->GetGroup() != 0xfffe ) 
2237          if (CurrentGroup != 0xfffe)
2238          { 
2239             int offset = Fp->tellg();//Only when heuristic for Explicit/Implicit was wrong
2240
2241             gdcmWarningMacro("Entry (" << newEntry->GetKey() << ") at x("
2242                      <<  offset << ") should be Explicit VR");
2243           }
2244       }
2245       newEntry->SetImplicitVR();
2246    }
2247
2248    try
2249    {
2250       FindDocEntryLength(newEntry);
2251    }
2252    catch ( FormatError )
2253    {
2254       // Call it quits
2255       newEntry->Delete();
2256       return 0;
2257    }
2258
2259    newEntry->SetOffset(Fp->tellg());  // for each DocEntry
2260    return newEntry;
2261 }
2262
2263 /**
2264  * \brief   Handle broken private tag from Philips NTSCAN
2265  *          where the endianess is being switched to BigEndian 
2266  *          for no apparent reason
2267  * @return  no return
2268  */
2269 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2270 {
2271  // for strange PMS Gyroscan Intera images
2272  // Item 'starter' has a tag : 0x3f3f,0x3f00, for no apparent reason
2273  
2274  // --- Feel free to remove this test *on your own coy of gdcm*
2275  //     if you are sure you'll never face this problem.
2276  
2277    if ((group == 0x3f3f) && (elem == 0x3f00))
2278    {
2279      // start endian swap mark for group found
2280      gdcmDebugMacro( " delimiter 0x3f3f  found." );
2281      // fix the tag
2282      group = 0xfffe;
2283      elem  = 0xe000;
2284      return;
2285    }
2286    // --- End of removable code
2287    
2288    // Endian reversion. 
2289    // Some files contain groups of tags with reversed endianess.
2290    static int reversedEndian = 0;
2291    // try to fix endian switching in the middle of headers
2292    if ((group == 0xfeff) && (elem == 0x00e0))
2293    {
2294      // start endian swap mark for group found
2295      gdcmDebugMacro( "Start endian swap mark found." );
2296      reversedEndian++;
2297      SwitchByteSwapCode();
2298      // fix the tag
2299      group = 0xfffe;
2300      elem  = 0xe000;
2301    } 
2302    else if (group == 0xfffe && elem == 0xe00d && reversedEndian) 
2303    {
2304      // end of reversed endian group
2305      gdcmDebugMacro( "End of reversed endian." );
2306      reversedEndian--;
2307      SwitchByteSwapCode();
2308    }
2309    else if (group == 0xfeff && elem == 0xdde0) 
2310    {
2311      // reversed Sequence Terminator found
2312      // probabely a bug in the header !
2313      // Do what you want, it breaks !
2314      //reversedEndian--;
2315      //SwitchByteSwapCode();
2316      gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2317      // fix the tag
2318       group = 0xfffe;
2319       elem  = 0xe0dd;  
2320    }
2321    else if (group == 0xfffe && elem == 0xe0dd) 
2322    {
2323       gdcmDebugMacro( "Straight Sequence Terminator." );  
2324    }
2325 }
2326
2327 /**
2328  * \brief   Group 0002 is always coded Little Endian
2329  *          whatever Transfer Syntax is
2330  * @return  no return
2331  */
2332 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2333 {
2334    // Endian reversion. 
2335    // Some files contain groups of tags with reversed endianess.
2336    
2337       Group0002Parsed = true;
2338       // we just came out of group 0002
2339       // if Transfer Syntax is Big Endian we have to change CheckSwap
2340
2341       std::string ts = GetTransferSyntax();
2342       TS::SpecialType s = Global::GetTS()->GetSpecialTransferSyntax(ts);
2343
2344       // Group 0002 is always 'Explicit ...' 
2345       // even when Transfer Syntax says 'Implicit ..." 
2346
2347       if ( s == TS::ImplicitVRLittleEndian 
2348         ||
2349           s == TS::ImplicitVRBigEndianPrivateGE  
2350          )
2351       {
2352          Filetype = ImplicitVR;
2353       }
2354        
2355       // FIXME Strangely, this works with 
2356       //'Implicit VR BigEndian Transfer Syntax' (GE Private)
2357       //
2358       // --> Probabely normal, since we considered we never have 
2359       // to trust manufacturers.
2360       // (we often find 'Implicit VR' tag, 
2361       // even when Transfer Syntax tells us it's Explicit ...
2362       
2363        // NEVER trust the meta elements!
2364        // (see what ezDICOM does ...)
2365              
2366       /*
2367       if ( s ==  TS::ExplicitVRBigEndian )
2368       {
2369          gdcmDebugMacro("Transfer Syntax Name = [" 
2370                         << GetTransferSyntaxName() << "]" );
2371          SwitchByteSwapCode();
2372          group = SwapShort(group);
2373          elem  = SwapShort(elem);
2374       }
2375       */
2376     //-- Broken ACR  may start with a Shadow Group --
2377     // worse : some ACR-NEMA like files start 00028 group ?!? 
2378     if ( !( (group >= 0x0001 && group <= 0x0008) || group == 0x0028 ) )
2379     {
2380        // We trust what we see.
2381        SwitchByteSwapCode();
2382        group = SwapShort(group);
2383        elem  = SwapShort(elem); 
2384        // not what we where told (by meta elements) !
2385        gdcmDebugMacro("Transfer Syntax Name = ["       
2386                        << GetTransferSyntaxName() << "]" );         
2387     }
2388       
2389       /// \todo  find a trick to warn user and stop processing
2390             
2391       if ( s == TS::DeflatedExplicitVRLittleEndian)
2392       {
2393            gdcmWarningMacro("Transfer Syntax [" 
2394                         << GetTransferSyntaxName() << "] :"
2395                         << " not yet dealt with ");
2396            return;       
2397       }
2398       
2399       // The following shouldn't occur very often
2400       // Let's check at the very end.
2401
2402       if ( ts == GDCM_UNKNOWN )
2403       {
2404          gdcmDebugMacro("True DICOM File, with NO Transfer Syntax (?!) " );
2405          return;      
2406       }
2407       
2408       if ( !Global::GetTS()->IsTransferSyntax(ts) )
2409       {
2410          gdcmWarningMacro("True DICOM File, with illegal Transfer Syntax: [" 
2411                           << ts << "]");
2412          return;
2413       }      
2414 }
2415
2416 //-----------------------------------------------------------------------------
2417 // Print
2418
2419 //-----------------------------------------------------------------------------
2420 } // end namespace gdcm