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