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