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