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