]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
* src/ : fix compilation warnings for the Write method (2 different
[gdcm.git] / src / gdcmDocument.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDocument.cxx,v $
5   Language:  C++
6   Date:      $Date: 2004/11/25 15:46:11 $
7   Version:   $Revision: 1.140 $
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
27 #include <vector>
28 #include <iomanip>
29
30 // For nthos:
31 #if defined(_MSC_VER) || defined(__BORLANDC__)
32    #include <winsock.h>
33 #else
34    #include <netinet/in.h>
35 #endif
36
37 namespace gdcm 
38 {
39 //-----------------------------------------------------------------------------
40 // Refer to Document::CheckSwap()
41 const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
42
43 // Refer to Document::SetMaxSizeLoadEntry()
44 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
45 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
46
47 //-----------------------------------------------------------------------------
48 // Constructor / Destructor
49
50 /**
51  * \brief   constructor  
52  * @param   filename file to be opened for parsing
53  */
54 Document::Document( std::string const & filename ) : ElementSet(-1)
55 {
56    SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE); 
57    Filename = filename;
58    Initialise();
59
60    Fp = 0;
61    if ( !OpenFile() )
62    {
63       return;
64    }
65
66    dbg.Verbose(0, "Document::Document: starting parsing of file: ",
67                   Filename.c_str());
68    Fp->seekg( 0,  std::ios_base::beg);
69    
70    Fp->seekg(0,  std::ios_base::end);
71    long lgt = Fp->tellg();
72            
73    Fp->seekg( 0,  std::ios_base::beg);
74    CheckSwap();
75    long beg = Fp->tellg();
76    lgt -= beg;
77    
78    ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
79
80    Fp->seekg( 0,  std::ios_base::beg);
81    
82    // Load 'non string' values
83       
84    std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);   
85    if( PhotometricInterpretation == "PALETTE COLOR " )
86    {
87       LoadEntryBinArea(0x0028,0x1200);  // gray LUT   
88       /// FIXME FIXME FIXME
89       /// The tags refered by the three following lines used to be CORRECTLY
90       /// defined as having an US Value Representation in the public
91       /// dictionnary. BUT the semantics implied by the three following
92       /// lines state that the corresponding tag contents are in fact
93       /// the ones of a BinEntry.
94       /// In order to fix things "Quick and Dirty" the dictionnary was
95       /// altered on PURPOUS but now contains a WRONG value.
96       /// In order to fix things and restore the dictionary to its
97       /// correct value, one needs to decided of the semantics by deciding
98       /// wether the following tags are either:
99       /// - multivaluated US, and hence loaded as ValEntry, but afterwards
100       ///   also used as BinEntry, which requires the proper conversion,
101       /// - OW, and hence loaded as BinEntry, but afterwards also used
102       ///   as ValEntry, which requires the proper conversion.
103       LoadEntryBinArea(0x0028,0x1201);  // R    LUT
104       LoadEntryBinArea(0x0028,0x1202);  // G    LUT
105       LoadEntryBinArea(0x0028,0x1203);  // B    LUT
106       
107       // Segmented Red   Palette Color LUT Data
108       LoadEntryBinArea(0x0028,0x1221);
109       // Segmented Green Palette Color LUT Data
110       LoadEntryBinArea(0x0028,0x1222);
111       // Segmented Blue  Palette Color LUT Data
112       LoadEntryBinArea(0x0028,0x1223);
113    } 
114    //FIXME later : how to use it?
115    LoadEntryBinArea(0x0028,0x3006);  //LUT Data (CTX dependent) 
116
117    CloseFile(); 
118   
119    // --------------------------------------------------------------
120    // Specific code to allow gdcm to read ACR-LibIDO formated images
121    // Note: ACR-LibIDO is an extension of the ACR standard that was
122    //       used at CREATIS. For the time being (say a couple years)
123    //       we keep this kludge to allow a smooth move to gdcm for
124    //       CREATIS developpers (sorry folks).
125    //
126    // if recognition code tells us we deal with a LibIDO image
127    // we switch lineNumber and columnNumber
128    //
129    std::string RecCode;
130    RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
131    if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
132        RecCode == "CANRME_AILIBOD1_1." )  // for brain-damaged softwares
133                                           // with "little-endian strings"
134    {
135          Filetype = ACR_LIBIDO; 
136          std::string rows    = GetEntryByNumber(0x0028, 0x0010);
137          std::string columns = GetEntryByNumber(0x0028, 0x0011);
138          SetEntryByNumber(columns, 0x0028, 0x0010);
139          SetEntryByNumber(rows   , 0x0028, 0x0011);
140    }
141    // ----------------- End of ACR-LibIDO kludge ------------------ 
142
143    PrintLevel = 1;  // 'Medium' print level by default
144 }
145
146 /**
147  * \brief This default constructor doesn't parse the file. You should
148  *        then invoke \ref Document::SetFileName and then the parsing.
149  */
150 Document::Document() : ElementSet(-1)
151 {
152    Fp = 0;
153
154    SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
155    Initialise();
156    SwapCode = 0;
157    Filetype = ExplicitVR;
158    PrintLevel = 1;  // 'Medium' print level by default
159 }
160
161 /**
162  * \brief   Canonical destructor.
163  */
164 Document::~Document ()
165 {
166    RefPubDict = NULL;
167    RefShaDict = NULL;
168
169    delete RLEInfo;
170    delete JPEGInfo;
171 }
172
173 //-----------------------------------------------------------------------------
174 // Print
175
176 /**
177   * \brief   Prints The Dict Entries of THE public Dicom Dictionary
178   * @return
179   */  
180 void Document::PrintPubDict(std::ostream & os)
181 {
182    RefPubDict->Print(os);
183 }
184
185 /**
186   * \brief   Prints The Dict Entries of THE shadow Dicom Dictionary
187   * @return
188   */
189 void Document::PrintShaDict(std::ostream & os)
190 {
191    RefShaDict->Print(os);
192 }
193
194 //-----------------------------------------------------------------------------
195 // Public
196 /**
197  * \brief   Get the public dictionary used
198  */
199 Dict* Document::GetPubDict()
200 {
201    return RefPubDict;
202 }
203
204 /**
205  * \brief   Get the shadow dictionary used
206  */
207 Dict* Document::GetShaDict()
208 {
209    return RefShaDict;
210 }
211
212 /**
213  * \brief   Set the shadow dictionary used
214  * \param   dict dictionary to use in shadow
215  */
216 bool Document::SetShaDict(Dict *dict)
217 {
218    RefShaDict = dict;
219    return !RefShaDict;
220 }
221
222 /**
223  * \brief   Set the shadow dictionary used
224  * \param   dictName name of the dictionary to use in shadow
225  */
226 bool Document::SetShaDict(DictKey const & dictName)
227 {
228    RefShaDict = Global::GetDicts()->GetDict(dictName);
229    return !RefShaDict;
230 }
231
232 /**
233  * \brief  This predicate, based on hopefully reasonable heuristics,
234  *         decides whether or not the current Document was properly parsed
235  *         and contains the mandatory information for being considered as
236  *         a well formed and usable Dicom/Acr File.
237  * @return true when Document is the one of a reasonable Dicom/Acr file,
238  *         false otherwise. 
239  */
240 bool Document::IsReadable()
241 {
242    if( Filetype == Unknown)
243    {
244       dbg.Verbose(0, "Document::IsReadable: wrong filetype");
245       return false;
246    }
247
248    if( TagHT.empty() )
249    {
250       dbg.Verbose(0, "Document::IsReadable: no tags in internal"
251                      " hash table.");
252       return false;
253    }
254
255    return true;
256 }
257
258 /**
259  * \brief   Accessor to the Transfer Syntax (when present) of the
260  *          current document (it internally handles reading the
261  *          value from disk when only parsing occured).
262  * @return  The encountered Transfer Syntax of the current document.
263  */
264 TransferSyntaxType Document::GetTransferSyntax()
265 {
266    DocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
267    if ( !entry )
268    {
269       return UnknownTS;
270    }
271
272    // The entry might be present but not loaded (parsing and loading
273    // happen at different stages): try loading and proceed with check...
274    LoadDocEntrySafe(entry);
275    if (ValEntry* valEntry = dynamic_cast< ValEntry* >(entry) )
276    {
277       std::string transfer = valEntry->GetValue();
278       // The actual transfer (as read from disk) might be padded. We
279       // first need to remove the potential padding. We can make the
280       // weak assumption that padding was not executed with digits...
281       if  ( transfer.length() == 0 )
282       {
283          // for brain damaged headers
284          return UnknownTS;
285       }
286       while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
287       {
288          transfer.erase(transfer.length()-1, 1);
289       }
290       for (int i = 0; TransferSyntaxStrings[i] != NULL; i++)
291       {
292          if ( TransferSyntaxStrings[i] == transfer )
293          {
294             return TransferSyntaxType(i);
295          }
296       }
297    }
298    return UnknownTS;
299 }
300
301 bool Document::IsJPEGLossless()
302 {
303    TransferSyntaxType r = GetTransferSyntax();
304    return    r ==  JPEGFullProgressionProcess10_12
305           || r == JPEGLosslessProcess14
306           || r == JPEGLosslessProcess14_1;
307 }
308                                                                                 
309 /**
310  * \brief   Determines if the Transfer Syntax was already encountered
311  *          and if it corresponds to a JPEG2000 one
312  * @return  True when JPEG2000 (Lossly or LossLess) found. False in all
313  *          other cases.
314  */
315 bool Document::IsJPEG2000()
316 {
317    TransferSyntaxType r = GetTransferSyntax();
318    return r == JPEG2000Lossless || r == JPEG2000;
319 }
320
321 /**
322  * \brief   Determines if the Transfer Syntax corresponds to any form
323  *          of Jpeg encoded Pixel data.
324  * @return  True when any form of JPEG found. False otherwise.
325  */
326 bool Document::IsJPEG()
327 {
328    TransferSyntaxType r = GetTransferSyntax();
329    return r == JPEGBaselineProcess1 
330      || r == JPEGExtendedProcess2_4
331      || r == JPEGExtendedProcess3_5
332      || r == JPEGSpectralSelectionProcess6_8
333      ||      IsJPEGLossless()
334      ||      IsJPEG2000();
335 }
336
337 /**
338  * \brief   Determines if the Transfer Syntax corresponds to encapsulated
339  *          of encoded Pixel Data (as opposed to native).
340  * @return  True when encapsulated. False when native.
341  */
342 bool Document::IsEncapsulate()
343 {
344    TransferSyntaxType r = GetTransferSyntax();
345    return IsJPEG() || r == RLELossless;
346 }
347
348 /**
349  * \brief   Predicate for dicom version 3 file.
350  * @return  True when the file is a dicom version 3.
351  */
352 bool Document::IsDicomV3()
353 {
354    // Checking if Transfert Syntax exists is enough
355    // Anyway, it's to late check if the 'Preamble' was found ...
356    // And ... would it be a rich idea to check ?
357    // (some 'no Preamble' DICOM images exist !)
358    return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
359 }
360
361 /**
362  * \brief  returns the File Type 
363  *         (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
364  * @return the FileType code
365  */
366 FileType Document::GetFileType()
367 {
368    return Filetype;
369 }
370
371 /**
372  * \brief  Tries to open the file \ref Document::Filename and
373  *         checks the preamble when existing.
374  * @return The FILE pointer on success. 
375  */
376 std::ifstream* Document::OpenFile()
377 {
378    if (Filename.length() == 0) return 0;
379    if(Fp)
380    {
381       dbg.Verbose( 0,
382                    "Document::OpenFile is already opened when opening: ",
383                    Filename.c_str());
384    }
385
386    Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
387
388    if(!Fp)
389    {
390       dbg.Verbose( 0,
391                    "Document::OpenFile cannot open file: ",
392                    Filename.c_str());
393       return 0;
394    }
395  
396    uint16_t zero;
397    Fp->read((char*)&zero,  (size_t)2 );
398  
399    //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
400    if( 
401        zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
402        zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
403        zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
404        zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
405    {
406       return Fp;
407    }
408  
409    //DICOM
410    Fp->seekg(126L, std::ios_base::cur);
411    char dicm[4];
412    Fp->read(dicm,  (size_t)4);
413    if( memcmp(dicm, "DICM", 4) == 0 )
414    {
415       return Fp;
416    }
417  
418    CloseFile();
419    dbg.Verbose( 0,
420                 "Document::OpenFile not DICOM/ACR (missing preamble)",
421                 Filename.c_str());
422  
423    return 0;
424 }
425
426 /**
427  * \brief closes the file  
428  * @return  TRUE if the close was successfull 
429  */
430 bool Document::CloseFile()
431 {
432    if( Fp )
433    {
434       Fp->close();
435       delete Fp;
436       Fp = 0;
437    }
438
439    return true; //FIXME how do we detect a non-close ifstream ?
440 }
441
442 /**
443  * \brief Writes in a file all the Header Entries (Dicom Elements) 
444  * @param fp file pointer on an already open file
445  * @param filetype Type of the File to be written 
446  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
447  * \return Always true.
448  */
449 void Document::WriteContent(std::ofstream* fp, FileType filetype)
450 {
451    /// \todo move the following lines (and a lot of others, to be written)
452    /// to a future function CheckAndCorrectHeader  
453    /// (necessary if user wants to write a DICOM V3 file
454    /// starting from an  ACR-NEMA (V2)  Header
455
456    if ( filetype == ImplicitVR || filetype == ExplicitVR )
457    {
458       // writing Dicom File Preamble
459       char filePreamble[128];
460       memset(filePreamble, 0, 128);
461       fp->write(filePreamble, 128);
462       fp->write("DICM", 4);
463    }
464
465 /**
466  * \todo rewrite later, if really usefull
467  *       - 'Group Length' element is optional in DICOM
468  *       - but un-updated odd groups lengthes can causes pb
469  *         (xmedcon breaker)
470  *
471  * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
472  *    UpdateGroupLength(false,filetype);
473  * if ( filetype == ACR)
474  *    UpdateGroupLength(true,ACR);
475  */
476  
477    ElementSet::WriteContent(fp, filetype); // This one is recursive
478 }
479
480 /**
481  * \brief   Modifies the value of a given Header Entry (Dicom Element)
482  *          when it exists. Create it with the given value when unexistant.
483  * @param   value (string) Value to be set
484  * @param   group   Group number of the Entry 
485  * @param   elem  Element number of the Entry
486  * @param   vr  V(alue) R(epresentation) of the Entry -if private Entry-
487  * \return  pointer to the modified/created Header Entry (NULL when creation
488  *          failed).
489  */ 
490 ValEntry* Document::ReplaceOrCreateByNumber(
491                                          std::string const & value, 
492                                          uint16_t group, 
493                                          uint16_t elem,
494                                          TagName const & vr )
495 {
496    ValEntry* valEntry = 0;
497    DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
498    
499    if (!currentEntry)
500    {
501       // check if (group,element) DictEntry exists
502       // if it doesn't, create an entry in DictSet::VirtualEntry
503       // and use it
504
505    // Find out if the tag we received is in the dictionaries:
506       Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
507       DictEntry* dictEntry = pubDict->GetDictEntryByNumber(group, elem);
508       if (!dictEntry)
509       {
510          currentEntry = NewDocEntryByNumber(group, elem, vr);
511       }
512       else
513       {
514          currentEntry = NewDocEntryByNumber(group, elem);
515       }
516
517       if (!currentEntry)
518       {
519          dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
520                         " NewDocEntryByNumber failed.");
521          return NULL;
522       }
523
524       valEntry = new ValEntry(currentEntry);
525       delete currentEntry;
526
527       if ( !AddEntry(valEntry))
528       {
529          delete valEntry;
530          dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
531                         " failed allthough this is a creation.");
532          return NULL;
533       }
534    }
535    else
536    {
537       valEntry = dynamic_cast< ValEntry* >(currentEntry);
538       if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
539                        // then we change it to a ValEntry ?
540                        // Shouldn't it be considered as an error ?
541       {
542          // We need to promote the DocEntry to a ValEntry:
543          valEntry = new ValEntry(currentEntry);
544          if (!RemoveEntry(currentEntry))
545          {
546             delete valEntry;
547             dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
548                            " of previous DocEntry failed.");
549             return NULL;
550          }
551          if ( !AddEntry(valEntry))
552          {
553             delete valEntry;
554             dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
555                            " promoted ValEntry failed.");
556             return NULL;
557          }
558       }
559    }
560
561    SetEntryByNumber(value, group, elem);
562
563    return valEntry;
564 }   
565
566 /*
567  * \brief   Modifies the value of a given Header Entry (Dicom Element)
568  *          when it exists. Create it with the given value when unexistant.
569  *          A copy of the binArea is made to be kept in the Document.
570  * @param   binArea (binary) value to be set
571  * @param   Group   Group number of the Entry 
572  * @param   Elem  Element number of the Entry
573  * \return  pointer to the modified/created Header Entry (NULL when creation
574  *          failed).
575  */
576 BinEntry* Document::ReplaceOrCreateByNumber(
577                                          uint8_t* binArea,
578                                          int lgth, 
579                                          uint16_t group, 
580                                          uint16_t elem,
581                                          TagName const & vr )
582 {
583    BinEntry* binEntry = 0;
584    DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
585    if (!currentEntry)
586    {
587
588       // check if (group,element) DictEntry exists
589       // if it doesn't, create an entry in DictSet::VirtualEntry
590       // and use it
591
592    // Find out if the tag we received is in the dictionaries:
593       Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
594       DictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
595
596       if (!dictEntry)
597       {
598          currentEntry = NewDocEntryByNumber(group, elem, vr);
599       }
600       else
601       {
602          currentEntry = NewDocEntryByNumber(group, elem);
603       }
604       if (!currentEntry)
605       {
606          dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
607                         " NewDocEntryByNumber failed.");
608          return NULL;
609       }
610       binEntry = new BinEntry(currentEntry);
611       if ( !AddEntry(binEntry))
612       {
613          dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
614                         " failed allthough this is a creation.");
615       }
616    }
617    else
618    {
619       binEntry = dynamic_cast< BinEntry* >(currentEntry);
620       if ( !binEntry ) // Euuuuh? It wasn't a BinEntry
621                        // then we change it to a BinEntry ?
622                        // Shouldn't it be considered as an error ?
623       {
624          // We need to promote the DocEntry to a BinEntry:
625          binEntry = new BinEntry(currentEntry);
626          if (!RemoveEntry(currentEntry))
627          {
628             dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
629                            " of previous DocEntry failed.");
630             return NULL;
631          }
632          if ( !AddEntry(binEntry))
633          {
634             dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
635                            " promoted BinEntry failed.");
636             return NULL;
637          }
638       }
639    }
640
641    uint8_t *tmpArea;
642    if (lgth>0 && binArea)
643    {
644       tmpArea = new uint8_t[lgth];
645       memcpy(tmpArea,binArea,lgth);
646    }
647    else
648    {
649       tmpArea = 0;
650    }
651    if (!SetEntryByNumber(tmpArea, lgth, group, elem))
652    {
653       if (tmpArea)
654       {
655          delete[] tmpArea;
656       }
657    }
658
659    return binEntry;
660 }  
661
662
663 /*
664  * \brief   Modifies the value of a given Header Entry (Dicom Element)
665  *          when it exists. Create it when unexistant.
666  * @param   Group   Group number of the Entry 
667  * @param   Elem  Element number of the Entry
668  * \return  pointer to the modified/created SeqEntry (NULL when creation
669  *          failed).
670  */
671 SeqEntry* Document::ReplaceOrCreateByNumber( uint16_t group, uint16_t elem)
672 {
673    SeqEntry* b = 0;
674    DocEntry* a = GetDocEntryByNumber( group, elem);
675    if (!a)
676    {
677       a = NewSeqEntryByNumber(group, elem);
678       if (!a)
679       {
680          return 0;
681       }
682
683       b = new SeqEntry(a, 1); // FIXME : 1 (Depth)
684       AddEntry(b);
685    }   
686    return b;
687
688  
689 /**
690  * \brief Set a new value if the invoked element exists
691  *        Seems to be useless !!!
692  * @param value new element value
693  * @param group  group number of the Entry 
694  * @param elem element number of the Entry
695  * \return  boolean 
696  */
697 bool Document::ReplaceIfExistByNumber(std::string const & value, 
698                                       uint16_t group, uint16_t elem ) 
699 {
700    SetEntryByNumber(value, group, elem);
701
702    return true;
703
704
705 //-----------------------------------------------------------------------------
706 // Protected
707
708 /**
709  * \brief   Checks if a given Dicom Element exists within the H table
710  * @param   group      Group number of the searched Dicom Element 
711  * @param   element  Element number of the searched Dicom Element 
712  * @return true is found
713  */
714 bool Document::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
715 {
716    const std::string &key = DictEntry::TranslateToKey(group, element );
717    return TagHT.count(key) != 0;
718 }
719
720 /**
721  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
722  *          the public and private dictionaries 
723  *          for the element value of a given tag.
724  * \warning Don't use any longer : use GetPubEntryByName
725  * @param   tagName name of the searched element.
726  * @return  Corresponding element value when it exists,
727  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
728  */
729 std::string Document::GetEntryByName(TagName const & tagName)
730 {
731    DictEntry* dictEntry = RefPubDict->GetDictEntryByName(tagName); 
732    if( !dictEntry )
733    {
734       return GDCM_UNFOUND;
735    }
736
737    return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
738 }
739
740 /**
741  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
742  *          the public and private dictionaries 
743  *          for the element value representation of a given tag.
744  *
745  *          Obtaining the VR (Value Representation) might be needed by caller
746  *          to convert the string typed content to caller's native type 
747  *          (think of C++ vs Python). The VR is actually of a higher level
748  *          of semantics than just the native C++ type.
749  * @param   tagName name of the searched element.
750  * @return  Corresponding element value representation when it exists,
751  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
752  */
753 std::string Document::GetEntryVRByName(TagName const& tagName)
754 {
755    DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
756    if( dictEntry == NULL)
757    {
758       return GDCM_UNFOUND;
759    }
760
761    DocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
762                                         dictEntry->GetElement());
763    return elem->GetVR();
764 }
765
766 /**
767  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
768  *          the public and private dictionaries 
769  *          for the element value representation of a given tag.
770  * @param   group Group number of the searched tag.
771  * @param   element Element number of the searched tag.
772  * @return  Corresponding element value representation when it exists,
773  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
774  */
775 std::string Document::GetEntryByNumber(uint16_t group, uint16_t element)
776 {
777    TagKey key = DictEntry::TranslateToKey(group, element);
778    /// \todo use map methods, instead of multimap JPR
779    if ( !TagHT.count(key))
780    {
781       return GDCM_UNFOUND;
782    }
783
784    return ((ValEntry *)TagHT.find(key)->second)->GetValue();
785 }
786
787 /**
788  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
789  *          the public and private dictionaries 
790  *          for the element value representation of a given tag..
791  *
792  *          Obtaining the VR (Value Representation) might be needed by caller
793  *          to convert the string typed content to caller's native type 
794  *          (think of C++ vs Python). The VR is actually of a higher level
795  *          of semantics than just the native C++ type.
796  * @param   group     Group number of the searched tag.
797  * @param   element Element number of the searched tag.
798  * @return  Corresponding element value representation when it exists,
799  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
800  */
801 std::string Document::GetEntryVRByNumber(uint16_t group, uint16_t element)
802 {
803    DocEntry* elem = GetDocEntryByNumber(group, element);
804    if ( !elem )
805    {
806       return GDCM_UNFOUND;
807    }
808    return elem->GetVR();
809 }
810
811 /**
812  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
813  *          the public and private dictionaries 
814  *          for the value length of a given tag..
815  * @param   group     Group number of the searched tag.
816  * @param   element Element number of the searched tag.
817  * @return  Corresponding element length; -2 if not found
818  */
819 int Document::GetEntryLengthByNumber(uint16_t group, uint16_t element)
820 {
821    DocEntry* elem =  GetDocEntryByNumber(group, element);
822    if ( !elem )
823    {
824       return -2;  //magic number
825    }
826    return elem->GetLength();
827 }
828 /**
829  * \brief   Sets the value (string) of the Header Entry (Dicom Element)
830  * @param   content string value of the Dicom Element
831  * @param   tagName name of the searched Dicom Element.
832  * @return  true when found
833  */
834 bool Document::SetEntryByName( std::string const & content,
835                                TagName const & tagName)
836 {
837    DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
838    if( !dictEntry )
839    {
840       return false;
841    }
842
843    return SetEntryByNumber(content,dictEntry->GetGroup(),
844                                    dictEntry->GetElement());
845 }
846
847 /**
848  * \brief   Accesses an existing DocEntry (i.e. a Dicom Element)
849  *          through it's (group, element) and modifies it's content with
850  *          the given value.
851  * @param   content new value (string) to substitute with
852  * @param   group     group number of the Dicom Element to modify
853  * @param   element element number of the Dicom Element to modify
854  */
855 bool Document::SetEntryByNumber(std::string const& content, 
856                                 uint16_t group, uint16_t element) 
857 {
858    int c;
859    int l;
860
861    ValEntry* valEntry = GetValEntryByNumber(group, element);
862    if (!valEntry )
863    {
864       dbg.Verbose(0, "Document::SetEntryByNumber: no corresponding",
865                      " ValEntry (try promotion first).");
866       return false;
867    }
868    // Non even content must be padded with a space (020H)...
869    std::string finalContent = Util::DicomString( content.c_str() );
870    assert( !(finalContent.size() % 2) );
871    valEntry->SetValue(finalContent);
872
873    // Integers have a special treatement for their length:
874
875    l = finalContent.length();
876    if ( l != 0) // To avoid to be cheated by 'zero length' integers
877    {   
878       VRKey vr = valEntry->GetVR();
879       if( vr == "US" || vr == "SS" )
880       {
881          // for multivaluated items
882          c = Util::CountSubstring(content, "\\") + 1;
883          l = c*2;
884       }
885       else if( vr == "UL" || vr == "SL" )
886       {
887          // for multivaluated items
888          c = Util::CountSubstring(content, "\\") + 1;
889          l = c*4;;
890       }
891    }
892    valEntry->SetLength(l);
893    return true;
894
895
896 /**
897  * \brief   Accesses an existing DocEntry (i.e. a Dicom Element)
898  *          through it's (group, element) and modifies it's content with
899  *          the given value.
900  * @param   content new value (void*  -> uint8_t*) to substitute with
901  * @param   lgth new value length
902  * @param   group     group number of the Dicom Element to modify
903  * @param   element element number of the Dicom Element to modify
904  */
905 bool Document::SetEntryByNumber(uint8_t*content, int lgth, 
906                                 uint16_t group, uint16_t element) 
907 {
908    (void)lgth;  //not used
909    TagKey key = DictEntry::TranslateToKey(group, element);
910    if ( !TagHT.count(key))
911    {
912       return false;
913    }
914
915 /* Hope Binary field length is *never* wrong    
916    if(lgth%2) // Non even length are padded with a space (020H).
917    {  
918       lgth++;
919       //content = content + '\0'; // fing a trick to enlarge a binary field?
920    }
921 */      
922    BinEntry* entry = (BinEntry *)TagHT[key];           
923    entry->SetBinArea(content);  
924    entry->SetLength(lgth);
925    entry->SetValue(GDCM_BINLOADED);
926
927    return true;
928
929
930 /**
931  * \brief   Accesses an existing DocEntry (i.e. a Dicom Element)
932  *          in the PubDocEntrySet of this instance
933  *          through it's (group, element) and modifies it's length with
934  *          the given value.
935  * \warning Use with extreme caution.
936  * @param l new length to substitute with
937  * @param group     group number of the Entry to modify
938  * @param element element number of the Entry to modify
939  * @return  true on success, false otherwise.
940  */
941 bool Document::SetEntryLengthByNumber(uint32_t l, 
942                                       uint16_t group, uint16_t element) 
943 {
944    /// \todo use map methods, instead of multimap JPR
945    TagKey key = DictEntry::TranslateToKey(group, element);
946    if ( !TagHT.count(key) )
947    {
948       return false;
949    }
950    if ( l % 2 )
951    {
952       l++; // length must be even
953    }
954    ( ((TagHT.equal_range(key)).first)->second )->SetLength(l); 
955
956    return true ;
957 }
958
959 /**
960  * \brief   Gets (from Header) the offset  of a 'non string' element value 
961  *          (LoadElementValues has already be executed)
962  * @param group   group number of the Entry 
963  * @param elem  element number of the Entry
964  * @return File Offset of the Element Value 
965  */
966 size_t Document::GetEntryOffsetByNumber(uint16_t group, uint16_t elem) 
967 {
968    DocEntry* entry = GetDocEntryByNumber(group, elem);
969    if (!entry) 
970    {
971       dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry present.");
972       return 0;
973    }
974    return entry->GetOffset();
975 }
976
977 /**
978  * \brief   Gets (from Header) a 'non string' element value 
979  *          (LoadElementValues has already be executed)  
980  * @param group   group number of the Entry 
981  * @param elem  element number of the Entry
982  * @return Pointer to the 'non string' area
983  */
984 void*  Document::GetEntryBinAreaByNumber(uint16_t group, uint16_t elem) 
985 {
986    DocEntry* entry = GetDocEntryByNumber(group, elem);
987    if (!entry) 
988    {
989       dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry");
990       return 0;
991    }
992    if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(entry) )
993    {
994       return binEntry->GetBinArea();
995    }
996
997    return 0;
998 }
999
1000 /**
1001  * \brief         Loads (from disk) the element content 
1002  *                when a string is not suitable
1003  * @param group   group number of the Entry 
1004  * @param elem  element number of the Entry
1005  */
1006 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
1007 {
1008    // Search the corresponding DocEntry
1009    DocEntry *docElement = GetDocEntryByNumber(group, elem);
1010    if ( !docElement )
1011       return;
1012
1013    BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
1014    if( !binElement )
1015       return;
1016
1017    LoadEntryBinArea(binElement);
1018 /*   size_t o =(size_t)docElement->GetOffset();
1019    Fp->seekg( o, std::ios_base::beg);
1020    size_t l = docElement->GetLength();
1021    uint8_t* a = new uint8_t[l];
1022    if(!a)
1023    {
1024       dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1025       return;
1026    }
1027
1028    // Read the value
1029    Fp->read((char*)a, l);
1030    if( Fp->fail() || Fp->eof() )//Fp->gcount() == 1
1031    {
1032       delete[] a;
1033       return;
1034    }
1035
1036    // Set the value to the DocEntry
1037    if( !SetEntryBinAreaByNumber( a, group, elem ) )
1038    {
1039       delete[] a;
1040       dbg.Verbose(0, "Document::LoadEntryBinArea setting failed.");
1041    }*/
1042 }
1043
1044 /**
1045  * \brief         Loads (from disk) the element content 
1046  *                when a string is not suitable
1047  * @param element  Entry whose binArea is going to be loaded
1048  */
1049 void Document::LoadEntryBinArea(BinEntry* element) 
1050 {
1051    if(element->GetBinArea())
1052       return;
1053
1054    bool openFile = !Fp;
1055    if(openFile)
1056       OpenFile();
1057
1058    size_t o =(size_t)element->GetOffset();
1059    Fp->seekg(o, std::ios_base::beg);
1060
1061    size_t l = element->GetLength();
1062    uint8_t* a = new uint8_t[l];
1063    if( !a )
1064    {
1065       dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1066       return;
1067    }
1068
1069    /// \todo check the result 
1070    Fp->read((char*)a, l);
1071    if( Fp->fail() || Fp->eof()) //Fp->gcount() == 1
1072    {
1073       delete[] a;
1074       return;
1075    }
1076
1077    element->SetBinArea(a);
1078
1079    if(openFile)
1080       CloseFile();
1081 }
1082
1083 /**
1084  * \brief   Sets a 'non string' value to a given Dicom Element
1085  * @param   area area containing the 'non string' value
1086  * @param   group     Group number of the searched Dicom Element 
1087  * @param   element Element number of the searched Dicom Element 
1088  * @return  
1089  */
1090 bool Document::SetEntryBinAreaByNumber(uint8_t* area,
1091                                        uint16_t group, uint16_t element) 
1092 {
1093    DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1094    if ( !currentEntry )
1095    {
1096       return false;
1097    }
1098
1099    if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1100    {
1101       binEntry->SetBinArea( area );
1102       return true;
1103    }
1104
1105    return false;
1106 }
1107
1108 /**
1109  * \brief   Update the entries with the shadow dictionary. 
1110  *          Only non even entries are analyzed       
1111  */
1112 void Document::UpdateShaEntries()
1113 {
1114    //DictEntry *entry;
1115    std::string vr;
1116    
1117    /// \todo TODO : still any use to explore recursively the whole structure?
1118 /*
1119    for(ListTag::iterator it=listEntries.begin();
1120        it!=listEntries.end();
1121        ++it)
1122    {
1123       // Odd group => from public dictionary
1124       if((*it)->GetGroup()%2==0)
1125          continue;
1126
1127       // Peer group => search the corresponding dict entry
1128       if(RefShaDict)
1129          entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1130       else
1131          entry=NULL;
1132
1133       if((*it)->IsImplicitVR())
1134          vr="Implicit";
1135       else
1136          vr=(*it)->GetVR();
1137
1138       (*it)->SetValue(GetDocEntryUnvalue(*it));  // to go on compiling
1139       if(entry){
1140          // Set the new entry and the new value
1141          (*it)->SetDictEntry(entry);
1142          CheckDocEntryVR(*it,vr);
1143
1144          (*it)->SetValue(GetDocEntryValue(*it));    // to go on compiling
1145  
1146       }
1147       else
1148       {
1149          // Remove precedent value transformation
1150          (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1151       }
1152    }
1153 */   
1154 }
1155
1156 /**
1157  * \brief   Searches within the Header Entries for a Dicom Element of
1158  *          a given tag.
1159  * @param   tagName name of the searched Dicom Element.
1160  * @return  Corresponding Dicom Element when it exists, and NULL
1161  *          otherwise.
1162  */
1163 DocEntry* Document::GetDocEntryByName(TagName const & tagName)
1164 {
1165    DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
1166    if( !dictEntry )
1167    {
1168       return NULL;
1169    }
1170
1171   return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1172 }
1173
1174 /**
1175  * \brief  retrieves a Dicom Element (the first one) using (group, element)
1176  * \warning (group, element) IS NOT an identifier inside the Dicom Header
1177  *           if you think it's NOT UNIQUE, check the count number
1178  *           and use iterators to retrieve ALL the Dicoms Elements within
1179  *           a given couple (group, element)
1180  * @param   group Group number of the searched Dicom Element 
1181  * @param   element Element number of the searched Dicom Element 
1182  * @return  
1183  */
1184 DocEntry* Document::GetDocEntryByNumber(uint16_t group, uint16_t element) 
1185 {
1186    TagKey key = DictEntry::TranslateToKey(group, element);
1187    if ( !TagHT.count(key))
1188    {
1189       return NULL;
1190    }
1191    return TagHT.find(key)->second;
1192 }
1193
1194 /**
1195  * \brief  Same as \ref Document::GetDocEntryByNumber except it only
1196  *         returns a result when the corresponding entry is of type
1197  *         ValEntry.
1198  * @return When present, the corresponding ValEntry. 
1199  */
1200 ValEntry* Document::GetValEntryByNumber(uint16_t group, uint16_t element)
1201 {
1202    DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1203    if ( !currentEntry )
1204    {
1205       return 0;
1206    }
1207    if ( ValEntry* valEntry = dynamic_cast<ValEntry*>(currentEntry) )
1208    {
1209       return valEntry;
1210    }
1211    dbg.Verbose(0, "Document::GetValEntryByNumber: unfound ValEntry.");
1212
1213    return 0;
1214 }
1215
1216 /**
1217  * \brief         Loads the element while preserving the current
1218  *                underlying file position indicator as opposed to
1219  *                to LoadDocEntry that modifies it.
1220  * @param entry   Header Entry whose value shall be loaded. 
1221  * @return  
1222  */
1223 void Document::LoadDocEntrySafe(DocEntry * entry)
1224 {
1225    if(Fp)
1226    {
1227       long PositionOnEntry = Fp->tellg();
1228       LoadDocEntry(entry);
1229       Fp->seekg(PositionOnEntry, std::ios_base::beg);
1230    }
1231 }
1232
1233 /**
1234  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
1235  *          processor order.
1236  * @return  The properly swaped 32 bits integer.
1237  */
1238 uint32_t Document::SwapLong(uint32_t a)
1239 {
1240    switch (SwapCode)
1241    {
1242       case    0 :
1243          break;
1244       case 4321 :
1245          a=( ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000) | 
1246              ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1247          break;
1248    
1249       case 3412 :
1250          a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1251          break;
1252    
1253       case 2143 :
1254          a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
1255          break;
1256       default :
1257          //std::cout << "swapCode= " << SwapCode << std::endl;
1258          dbg.Error(" Document::SwapLong : unset swap code");
1259          a = 0;
1260    }
1261    return a;
1262
1263
1264 /**
1265  * \brief   Unswaps back the bytes of 4-byte long integer accordingly to
1266  *          processor order.
1267  * @return  The properly unswaped 32 bits integer.
1268  */
1269 uint32_t Document::UnswapLong(uint32_t a)
1270 {
1271    return SwapLong(a);
1272 }
1273
1274 /**
1275  * \brief   Swaps the bytes so they agree with the processor order
1276  * @return  The properly swaped 16 bits integer.
1277  */
1278 uint16_t Document::SwapShort(uint16_t a)
1279 {
1280    if ( SwapCode == 4321 || SwapCode == 2143 )
1281    {
1282       a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1283    }
1284    return a;
1285 }
1286
1287 /**
1288  * \brief   Unswaps the bytes so they agree with the processor order
1289  * @return  The properly unswaped 16 bits integer.
1290  */
1291 uint16_t Document::UnswapShort(uint16_t a)
1292 {
1293    return SwapShort(a);
1294 }
1295
1296 //-----------------------------------------------------------------------------
1297 // Private
1298
1299 /**
1300  * \brief   Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1301  * @return  length of the parsed set. 
1302  */ 
1303 void Document::ParseDES(DocEntrySet *set, long offset, 
1304                         long l_max, bool delim_mode)
1305 {
1306    DocEntry *newDocEntry = 0;
1307
1308    while (true)
1309    {
1310       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1311       {
1312          break;
1313       }
1314       newDocEntry = ReadNextDocEntry( );
1315       if ( !newDocEntry )
1316       {
1317          break;
1318       }
1319
1320       VRKey vr = newDocEntry->GetVR();
1321       if ( vr != "SQ" )
1322       {
1323                
1324          if ( Global::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1325          {
1326          /////////////////////// ValEntry
1327             ValEntry* newValEntry =
1328                new ValEntry( newDocEntry->GetDictEntry() ); //LEAK
1329             newValEntry->Copy( newDocEntry );
1330              
1331             // When "set" is a Document, then we are at the top of the
1332             // hierarchy and the Key is simply of the form ( group, elem )...
1333             if (Document* dummy = dynamic_cast< Document* > ( set ) )
1334             {
1335                (void)dummy;
1336                newValEntry->SetKey( newValEntry->GetKey() );
1337             }
1338             // ...but when "set" is a SQItem, we are inserting this new
1339             // valEntry in a sequence item. Hence the key has the
1340             // generalized form (refer to \ref BaseTagKey):
1341             if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1342             {
1343                newValEntry->SetKey(  parentSQItem->GetBaseTagKey()
1344                                    + newValEntry->GetKey() );
1345             }
1346              
1347             LoadDocEntry( newValEntry );
1348             bool delimitor=newValEntry->IsItemDelimitor();
1349             if( !set->AddEntry( newValEntry ) )
1350             {
1351               // If here expect big troubles
1352               delete newValEntry; //otherwise mem leak
1353             }
1354
1355             if (delimitor)
1356             {
1357                delete newDocEntry;
1358                break;
1359             }
1360             if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1361             {
1362                delete newDocEntry;
1363                break;
1364             }
1365          }
1366          else
1367          {
1368             if ( ! Global::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1369             { 
1370                 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1371                 dbg.Verbose(0, "Document::ParseDES: neither Valentry, "
1372                                "nor BinEntry. Probably unknown VR.");
1373             }
1374
1375          //////////////////// BinEntry or UNKOWN VR:
1376             BinEntry* newBinEntry = new BinEntry( newDocEntry );  //LEAK
1377
1378             // When "this" is a Document the Key is simply of the
1379             // form ( group, elem )...
1380             if (Document* dummy = dynamic_cast< Document* > ( set ) )
1381             {
1382                (void)dummy;
1383                newBinEntry->SetKey( newBinEntry->GetKey() );
1384             }
1385             // but when "this" is a SQItem, we are inserting this new
1386             // valEntry in a sequence item, and the kay has the
1387             // generalized form (refer to \ref BaseTagKey):
1388             if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1389             {
1390                newBinEntry->SetKey(  parentSQItem->GetBaseTagKey()
1391                                    + newBinEntry->GetKey() );
1392             }
1393
1394             LoadDocEntry( newBinEntry );
1395             if( !set->AddEntry( newBinEntry ) )
1396             {
1397               //Expect big troubles if here
1398               delete newBinEntry;
1399             }
1400          }
1401
1402          if (    ( newDocEntry->GetGroup()   == 0x7fe0 )
1403               && ( newDocEntry->GetElement() == 0x0010 ) )
1404          {
1405              TransferSyntaxType ts = GetTransferSyntax();
1406              if ( ts == RLELossless ) 
1407              {
1408                 long PositionOnEntry = Fp->tellg();
1409                 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1410                 ComputeRLEInfo();
1411                 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1412              }
1413              else if ( IsJPEG() )
1414              {
1415                 long PositionOnEntry = Fp->tellg();
1416                 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1417                 ComputeJPEGFragmentInfo();
1418                 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1419              }
1420          }
1421     
1422          // Just to make sure we are at the beginning of next entry.
1423          SkipToNextDocEntry(newDocEntry);
1424          //delete newDocEntry;
1425       }
1426       else
1427       {
1428          // VR = "SQ"
1429          unsigned long l = newDocEntry->GetReadLength();            
1430          if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1431          {
1432             if ( l == 0xffffffff )
1433             {
1434               delim_mode = true;
1435             }
1436             else
1437             {
1438               delim_mode = false;
1439             }
1440          }
1441          // no other way to create it ...
1442          SeqEntry* newSeqEntry =
1443             new SeqEntry( newDocEntry->GetDictEntry() );
1444          newSeqEntry->Copy( newDocEntry );
1445          newSeqEntry->SetDelimitorMode( delim_mode );
1446
1447          // At the top of the hierarchy, stands a Document. When "set"
1448          // is a Document, then we are building the first depth level.
1449          // Hence the SeqEntry we are building simply has a depth
1450          // level of one:
1451          if (Document* dummy = dynamic_cast< Document* > ( set ) )
1452          {
1453             (void)dummy;
1454             newSeqEntry->SetDepthLevel( 1 );
1455             newSeqEntry->SetKey( newSeqEntry->GetKey() );
1456          }
1457          // But when "set" is allready a SQItem, we are building a nested
1458          // sequence, and hence the depth level of the new SeqEntry
1459          // we are building, is one level deeper:
1460          if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1461          {
1462             newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1463             newSeqEntry->SetKey(  parentSQItem->GetBaseTagKey()
1464                                 + newSeqEntry->GetKey() );
1465          }
1466
1467          if ( l != 0 )
1468          {  // Don't try to parse zero-length sequences
1469             ParseSQ( newSeqEntry, 
1470                      newDocEntry->GetOffset(),
1471                      l, delim_mode);
1472          }
1473          set->AddEntry( newSeqEntry );
1474          if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1475          {
1476             delete newDocEntry;
1477             break;
1478          }
1479       }
1480       delete newDocEntry;
1481    }
1482 }
1483
1484 /**
1485  * \brief   Parses a Sequence ( SeqEntry after SeqEntry)
1486  * @return  parsed length for this level
1487  */ 
1488 void Document::ParseSQ( SeqEntry* seqEntry,
1489                         long offset, long l_max, bool delim_mode)
1490 {
1491    int SQItemNumber = 0;
1492    bool dlm_mod;
1493
1494    while (true)
1495    {
1496       DocEntry* newDocEntry = ReadNextDocEntry();   
1497       if ( !newDocEntry )
1498       {
1499          // FIXME Should warn user
1500          break;
1501       }
1502       if( delim_mode )
1503       {
1504          if ( newDocEntry->IsSequenceDelimitor() )
1505          {
1506             seqEntry->SetSequenceDelimitationItem( newDocEntry ); 
1507             break;
1508          }
1509       }
1510       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1511       {
1512          delete newDocEntry;
1513          break;
1514       }
1515
1516       SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1517       std::ostringstream newBase;
1518       newBase << seqEntry->GetKey()
1519               << "/"
1520               << SQItemNumber
1521               << "#";
1522       itemSQ->SetBaseTagKey( newBase.str() );
1523       unsigned int l = newDocEntry->GetReadLength();
1524       
1525       if ( l == 0xffffffff )
1526       {
1527          dlm_mod = true;
1528       }
1529       else
1530       {
1531          dlm_mod = false;
1532       }
1533    
1534       ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1535       delete newDocEntry;
1536       
1537       seqEntry->AddEntry( itemSQ, SQItemNumber ); 
1538       SQItemNumber++;
1539       if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1540       {
1541          break;
1542       }
1543    }
1544 }
1545
1546 /**
1547  * \brief         Loads the element content if its length doesn't exceed
1548  *                the value specified with Document::SetMaxSizeLoadEntry()
1549  * @param         entry Header Entry (Dicom Element) to be dealt with
1550  */
1551 void Document::LoadDocEntry(DocEntry* entry)
1552 {
1553    uint16_t group  = entry->GetGroup();
1554    std::string  vr = entry->GetVR();
1555    uint32_t length = entry->GetLength();
1556
1557    Fp->seekg((long)entry->GetOffset(), std::ios_base::beg);
1558
1559    // A SeQuence "contains" a set of Elements.  
1560    //          (fffe e000) tells us an Element is beginning
1561    //          (fffe e00d) tells us an Element just ended
1562    //          (fffe e0dd) tells us the current SeQuence just ended
1563    if( group == 0xfffe )
1564    {
1565       // NO more value field for SQ !
1566       return;
1567    }
1568
1569    // When the length is zero things are easy:
1570    if ( length == 0 )
1571    {
1572       ((ValEntry *)entry)->SetValue("");
1573       return;
1574    }
1575
1576    // The elements whose length is bigger than the specified upper bound
1577    // are not loaded. Instead we leave a short notice of the offset of
1578    // the element content and it's length.
1579
1580    std::ostringstream s;
1581    if (length > MaxSizeLoadEntry)
1582    {
1583       if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1584       {  
1585          //s << "gdcm::NotLoaded (BinEntry)";
1586          s << GDCM_NOTLOADED;
1587          s << " Address:" << (long)entry->GetOffset();
1588          s << " Length:"  << entry->GetLength();
1589          s << " x(" << std::hex << entry->GetLength() << ")";
1590          binEntryPtr->SetValue(s.str());
1591       }
1592       // Be carefull : a BinEntry IS_A ValEntry ... 
1593       else if (ValEntry* valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1594       {
1595         // s << "gdcm::NotLoaded. (ValEntry)";
1596          s << GDCM_NOTLOADED;  
1597          s << " Address:" << (long)entry->GetOffset();
1598          s << " Length:"  << entry->GetLength();
1599          s << " x(" << std::hex << entry->GetLength() << ")";
1600          valEntryPtr->SetValue(s.str());
1601       }
1602       else
1603       {
1604          // fusible
1605          std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1606                   << "nor a ValEntry ?! Should never print that !" << std::endl;
1607       }
1608
1609       // to be sure we are at the end of the value ...
1610       Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1611                 std::ios_base::beg);
1612       return;
1613    }
1614
1615    // When we find a BinEntry not very much can be done :
1616    if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1617    {
1618       s << GDCM_BINLOADED;
1619       binEntryPtr->SetValue(s.str());
1620       LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1621       return;
1622    }
1623     
1624    /// \todo Any compacter code suggested (?)
1625    if ( IsDocEntryAnInteger(entry) )
1626    {   
1627       uint32_t NewInt;
1628       int nbInt;
1629       // When short integer(s) are expected, read and convert the following 
1630       // n *two characters properly i.e. consider them as short integers as
1631       // opposed to strings.
1632       // Elements with Value Multiplicity > 1
1633       // contain a set of integers (not a single one)       
1634       if (vr == "US" || vr == "SS")
1635       {
1636          nbInt = length / 2;
1637          NewInt = ReadInt16();
1638          s << NewInt;
1639          if (nbInt > 1)
1640          {
1641             for (int i=1; i < nbInt; i++)
1642             {
1643                s << '\\';
1644                NewInt = ReadInt16();
1645                s << NewInt;
1646             }
1647          }
1648       }
1649       // See above comment on multiple integers (mutatis mutandis).
1650       else if (vr == "UL" || vr == "SL")
1651       {
1652          nbInt = length / 4;
1653          NewInt = ReadInt32();
1654          s << NewInt;
1655          if (nbInt > 1)
1656          {
1657             for (int i=1; i < nbInt; i++)
1658             {
1659                s << '\\';
1660                NewInt = ReadInt32();
1661                s << NewInt;
1662             }
1663          }
1664       }
1665 #ifdef GDCM_NO_ANSI_STRING_STREAM
1666       s << std::ends; // to avoid oddities on Solaris
1667 #endif //GDCM_NO_ANSI_STRING_STREAM
1668
1669       ((ValEntry *)entry)->SetValue(s.str());
1670       return;
1671    }
1672    
1673   // FIXME: We need an additional byte for storing \0 that is not on disk
1674    char *str = new char[length+1];
1675    Fp->read(str, (size_t)length);
1676    str[length] = '\0'; //this is only useful when length is odd
1677    // Special DicomString call to properly handle \0 and even length
1678    std::string newValue;
1679    if( length % 2 )
1680    {
1681       newValue = Util::DicomString(str, length+1);
1682       //dbg.Verbose(0, "Warning: bad length: ", length );
1683       dbg.Verbose(0, "For string :",  newValue.c_str()); 
1684       // Since we change the length of string update it length
1685       entry->SetReadLength(length+1);
1686    }
1687    else
1688    {
1689       newValue = Util::DicomString(str, length);
1690    }
1691    delete[] str;
1692
1693    if ( ValEntry* valEntry = dynamic_cast<ValEntry* >(entry) )
1694    {
1695       if ( Fp->fail() || Fp->eof())//Fp->gcount() == 1
1696       {
1697          dbg.Verbose(1, "Document::LoadDocEntry",
1698                         "unread element value");
1699          valEntry->SetValue(GDCM_UNREAD);
1700          return;
1701       }
1702
1703       if( vr == "UI" )
1704       {
1705          // Because of correspondance with the VR dic
1706          valEntry->SetValue(newValue);
1707       }
1708       else
1709       {
1710          valEntry->SetValue(newValue);
1711       }
1712    }
1713    else
1714    {
1715       dbg.Error(true, "Document::LoadDocEntry"
1716                       "Should have a ValEntry, here !");
1717    }
1718 }
1719
1720
1721 /**
1722  * \brief  Find the value Length of the passed Header Entry
1723  * @param  entry Header Entry whose length of the value shall be loaded. 
1724  */
1725 void Document::FindDocEntryLength( DocEntry *entry )
1726    throw ( FormatError )
1727 {
1728    uint16_t element = entry->GetElement();
1729    std::string  vr  = entry->GetVR();
1730    uint16_t length16;       
1731    
1732    if ( Filetype == ExplicitVR && !entry->IsImplicitVR() ) 
1733    {
1734       if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" ) 
1735       {
1736          // The following reserved two bytes (see PS 3.5-2003, section
1737          // "7.1.2 Data element structure with explicit vr", p 27) must be
1738          // skipped before proceeding on reading the length on 4 bytes.
1739          Fp->seekg( 2L, std::ios_base::cur);
1740          uint32_t length32 = ReadInt32();
1741
1742          if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff ) 
1743          {
1744             uint32_t lengthOB;
1745             try 
1746             {
1747                /// \todo rename that to FindDocEntryLengthOBOrOW since
1748                ///       the above test is on both OB and OW...
1749                lengthOB = FindDocEntryLengthOB();
1750             }
1751             catch ( FormatUnexpected )
1752             {
1753                // Computing the length failed (this happens with broken
1754                // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1755                // chance to get the pixels by deciding the element goes
1756                // until the end of the file. Hence we artificially fix the
1757                // the length and proceed.
1758                long currentPosition = Fp->tellg();
1759                Fp->seekg(0L,std::ios_base::end);
1760                long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1761                Fp->seekg(currentPosition, std::ios_base::beg);
1762                entry->SetLength(lengthUntilEOF);
1763                return;
1764             }
1765             entry->SetLength(lengthOB);
1766             return;
1767          }
1768          FixDocEntryFoundLength(entry, length32); 
1769          return;
1770       }
1771
1772       // Length is encoded on 2 bytes.
1773       length16 = ReadInt16();
1774       
1775       // We can tell the current file is encoded in big endian (like
1776       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1777       // and it's value is the one of the encoding of a big endian file.
1778       // In order to deal with such big endian encoded files, we have
1779       // (at least) two strategies:
1780       // * when we load the "Transfer Syntax" tag with value of big endian
1781       //   encoding, we raise the proper flags. Then we wait for the end
1782       //   of the META group (0x0002) among which is "Transfer Syntax",
1783       //   before switching the swap code to big endian. We have to postpone
1784       //   the switching of the swap code since the META group is fully encoded
1785       //   in little endian, and big endian coding only starts at the next
1786       //   group. The corresponding code can be hard to analyse and adds
1787       //   many additional unnecessary tests for regular tags.
1788       // * the second strategy consists in waiting for trouble, that shall
1789       //   appear when we find the first group with big endian encoding. This
1790       //   is easy to detect since the length of a "Group Length" tag (the
1791       //   ones with zero as element number) has to be of 4 (0x0004). When we
1792       //   encounter 1024 (0x0400) chances are the encoding changed and we
1793       //   found a group with big endian encoding.
1794       // We shall use this second strategy. In order to make sure that we
1795       // can interpret the presence of an apparently big endian encoded
1796       // length of a "Group Length" without committing a big mistake, we
1797       // add an additional check: we look in the already parsed elements
1798       // for the presence of a "Transfer Syntax" whose value has to be "big
1799       // endian encoding". When this is the case, chances are we have got our
1800       // hands on a big endian encoded file: we switch the swap code to
1801       // big endian and proceed...
1802       if ( element  == 0x0000 && length16 == 0x0400 ) 
1803       {
1804          TransferSyntaxType ts = GetTransferSyntax();
1805          if ( ts != ExplicitVRBigEndian ) 
1806          {
1807             throw FormatError( "Document::FindDocEntryLength()",
1808                                " not explicit VR." );
1809             return;
1810          }
1811          length16 = 4;
1812          SwitchSwapToBigEndian();
1813          // Restore the unproperly loaded values i.e. the group, the element
1814          // and the dictionary entry depending on them.
1815          uint16_t correctGroup = SwapShort( entry->GetGroup() );
1816          uint16_t correctElem  = SwapShort( entry->GetElement() );
1817          DictEntry* newTag = GetDictEntryByNumber( correctGroup,
1818                                                        correctElem );
1819          if ( !newTag )
1820          {
1821             // This correct tag is not in the dictionary. Create a new one.
1822             newTag = NewVirtualDictEntry(correctGroup, correctElem);
1823          }
1824          // FIXME this can create a memory leaks on the old entry that be
1825          // left unreferenced.
1826          entry->SetDictEntry( newTag );
1827       }
1828        
1829       // Heuristic: well, some files are really ill-formed.
1830       if ( length16 == 0xffff) 
1831       {
1832          // 0xffff means that we deal with 'Unknown Length' Sequence  
1833          length16 = 0;
1834       }
1835       FixDocEntryFoundLength( entry, (uint32_t)length16 );
1836       return;
1837    }
1838    else
1839    {
1840       // Either implicit VR or a non DICOM conformal (see note below) explicit
1841       // VR that ommited the VR of (at least) this element. Farts happen.
1842       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1843       // on Data elements "Implicit and Explicit VR Data Elements shall
1844       // not coexist in a Data Set and Data Sets nested within it".]
1845       // Length is on 4 bytes.
1846       
1847       FixDocEntryFoundLength( entry, ReadInt32() );
1848       return;
1849    }
1850 }
1851
1852 /**
1853  * \brief     Find the Value Representation of the current Dicom Element.
1854  * @param     entry
1855  */
1856 void Document::FindDocEntryVR( DocEntry *entry )
1857 {
1858    if ( Filetype != ExplicitVR )
1859    {
1860       return;
1861    }
1862
1863    char vr[3];
1864
1865    long positionOnEntry = Fp->tellg();
1866    // Warning: we believe this is explicit VR (Value Representation) because
1867    // we used a heuristic that found "UL" in the first tag. Alas this
1868    // doesn't guarantee that all the tags will be in explicit VR. In some
1869    // cases (see e-film filtered files) one finds implicit VR tags mixed
1870    // within an explicit VR file. Hence we make sure the present tag
1871    // is in explicit VR and try to fix things if it happens not to be
1872    // the case.
1873    
1874    Fp->read (vr, (size_t)2);
1875    vr[2] = 0;
1876
1877    if( !CheckDocEntryVR(entry, vr) )
1878    {
1879       Fp->seekg(positionOnEntry, std::ios_base::beg);
1880       // When this element is known in the dictionary we shall use, e.g. for
1881       // the semantics (see the usage of IsAnInteger), the VR proposed by the
1882       // dictionary entry. Still we have to flag the element as implicit since
1883       // we know now our assumption on expliciteness is not furfilled.
1884       // avoid  .
1885       if ( entry->IsVRUnknown() )
1886       {
1887          entry->SetVR("Implicit");
1888       }
1889       entry->SetImplicitVR();
1890    }
1891 }
1892
1893 /**
1894  * \brief     Check the correspondance between the VR of the header entry
1895  *            and the taken VR. If they are different, the header entry is 
1896  *            updated with the new VR.
1897  * @param     entry Header Entry to check
1898  * @param     vr    Dicom Value Representation
1899  * @return    false if the VR is incorrect of if the VR isn't referenced
1900  *            otherwise, it returns true
1901 */
1902 bool Document::CheckDocEntryVR(DocEntry *entry, VRKey vr)
1903 {
1904    std::string msg;
1905    bool realExplicit = true;
1906
1907    // Assume we are reading a falsely explicit VR file i.e. we reached
1908    // a tag where we expect reading a VR but are in fact we read the
1909    // first to bytes of the length. Then we will interogate (through find)
1910    // the dicom_vr dictionary with oddities like "\004\0" which crashes
1911    // both GCC and VC++ implementations of the STL map. Hence when the
1912    // expected VR read happens to be non-ascii characters we consider
1913    // we hit falsely explicit VR tag.
1914
1915    if ( !isalpha((unsigned char)vr[0]) && !isalpha((unsigned char)vr[1]) )
1916    {
1917       realExplicit = false;
1918    }
1919
1920    // CLEANME searching the dicom_vr at each occurence is expensive.
1921    // PostPone this test in an optional integrity check at the end
1922    // of parsing or only in debug mode.
1923    if ( realExplicit && !Global::GetVR()->Count(vr) )
1924    {
1925       realExplicit = false;
1926    }
1927
1928    if ( !realExplicit ) 
1929    {
1930       // We thought this was explicit VR, but we end up with an
1931       // implicit VR tag. Let's backtrack.   
1932       msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n", 
1933                     entry->GetGroup(), entry->GetElement());
1934       dbg.Verbose(1, "Document::FindVR: ", msg.c_str());
1935
1936       if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1937       {
1938          // Group length is UL !
1939          DictEntry* newEntry = NewVirtualDictEntry(
1940                                    entry->GetGroup(), entry->GetElement(),
1941                                    "UL", "FIXME", "Group Length");
1942          entry->SetDictEntry( newEntry );
1943       }
1944       return false;
1945    }
1946
1947    if ( entry->IsVRUnknown() )
1948    {
1949       // When not a dictionary entry, we can safely overwrite the VR.
1950       if( entry->GetElement() == 0x0000 )
1951       {
1952          // Group length is UL !
1953          entry->SetVR("UL");
1954       }
1955       else
1956       {
1957          entry->SetVR(vr);
1958       }
1959    }
1960    else if ( entry->GetVR() != vr ) 
1961    {
1962       // The VR present in the file and the dictionary disagree. We assume
1963       // the file writer knew best and use the VR of the file. Since it would
1964       // be unwise to overwrite the VR of a dictionary (since it would
1965       // compromise it's next user), we need to clone the actual DictEntry
1966       // and change the VR for the read one.
1967       DictEntry* newEntry = NewVirtualDictEntry(
1968                                 entry->GetGroup(), entry->GetElement(),
1969                                 vr, "FIXME", entry->GetName());
1970       entry->SetDictEntry(newEntry);
1971    }
1972
1973    return true; 
1974 }
1975
1976 /**
1977  * \brief   Get the transformed value of the header entry. The VR value 
1978  *          is used to define the transformation to operate on the value
1979  * \warning NOT end user intended method !
1980  * @param   entry entry to tranform
1981  * @return  Transformed entry value
1982  */
1983 std::string Document::GetDocEntryValue(DocEntry *entry)
1984 {
1985    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1986    {
1987       std::string val = ((ValEntry *)entry)->GetValue();
1988       std::string vr  = entry->GetVR();
1989       uint32_t length = entry->GetLength();
1990       std::ostringstream s;
1991       int nbInt;
1992
1993       // When short integer(s) are expected, read and convert the following 
1994       // n * 2 bytes properly i.e. as a multivaluated strings
1995       // (each single value is separated fromthe next one by '\'
1996       // as usual for standard multivaluated filels
1997       // Elements with Value Multiplicity > 1
1998       // contain a set of short integers (not a single one) 
1999    
2000       if( vr == "US" || vr == "SS" )
2001       {
2002          uint16_t newInt16;
2003
2004          nbInt = length / 2;
2005          for (int i=0; i < nbInt; i++) 
2006          {
2007             if( i != 0 )
2008             {
2009                s << '\\';
2010             }
2011             newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2012             newInt16 = SwapShort( newInt16 );
2013             s << newInt16;
2014          }
2015       }
2016
2017       // When integer(s) are expected, read and convert the following 
2018       // n * 4 bytes properly i.e. as a multivaluated strings
2019       // (each single value is separated fromthe next one by '\'
2020       // as usual for standard multivaluated filels
2021       // Elements with Value Multiplicity > 1
2022       // contain a set of integers (not a single one) 
2023       else if( vr == "UL" || vr == "SL" )
2024       {
2025          uint32_t newInt32;
2026
2027          nbInt = length / 4;
2028          for (int i=0; i < nbInt; i++) 
2029          {
2030             if( i != 0)
2031             {
2032                s << '\\';
2033             }
2034             newInt32 = ( val[4*i+0] & 0xFF )
2035                     + (( val[4*i+1] & 0xFF ) <<  8 )
2036                     + (( val[4*i+2] & 0xFF ) << 16 )
2037                     + (( val[4*i+3] & 0xFF ) << 24 );
2038             newInt32 = SwapLong( newInt32 );
2039             s << newInt32;
2040          }
2041       }
2042 #ifdef GDCM_NO_ANSI_STRING_STREAM
2043       s << std::ends; // to avoid oddities on Solaris
2044 #endif //GDCM_NO_ANSI_STRING_STREAM
2045       return s.str();
2046    }
2047
2048    return ((ValEntry *)entry)->GetValue();
2049 }
2050
2051 /**
2052  * \brief   Get the reverse transformed value of the header entry. The VR 
2053  *          value is used to define the reverse transformation to operate on
2054  *          the value
2055  * \warning NOT end user intended method !
2056  * @param   entry Entry to reverse transform
2057  * @return  Reverse transformed entry value
2058  */
2059 std::string Document::GetDocEntryUnvalue(DocEntry* entry)
2060 {
2061    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2062    {
2063       std::string vr = entry->GetVR();
2064       std::vector<std::string> tokens;
2065       std::ostringstream s;
2066
2067       if ( vr == "US" || vr == "SS" ) 
2068       {
2069          uint16_t newInt16;
2070
2071          tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2072          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2073          for (unsigned int i=0; i<tokens.size(); i++) 
2074          {
2075             newInt16 = atoi(tokens[i].c_str());
2076             s << (  newInt16        & 0xFF ) 
2077               << (( newInt16 >> 8 ) & 0xFF );
2078          }
2079          tokens.clear();
2080       }
2081       if ( vr == "UL" || vr == "SL")
2082       {
2083          uint32_t newInt32;
2084
2085          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2086          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2087          for (unsigned int i=0; i<tokens.size();i++) 
2088          {
2089             newInt32 = atoi(tokens[i].c_str());
2090             s << (char)(  newInt32         & 0xFF ) 
2091               << (char)(( newInt32 >>  8 ) & 0xFF )
2092               << (char)(( newInt32 >> 16 ) & 0xFF )
2093               << (char)(( newInt32 >> 24 ) & 0xFF );
2094          }
2095          tokens.clear();
2096       }
2097
2098 #ifdef GDCM_NO_ANSI_STRING_STREAM
2099       s << std::ends; // to avoid oddities on Solaris
2100 #endif //GDCM_NO_ANSI_STRING_STREAM
2101       return s.str();
2102    }
2103
2104    return ((ValEntry *)entry)->GetValue();
2105 }
2106
2107 /**
2108  * \brief   Skip a given Header Entry 
2109  * \warning NOT end user intended method !
2110  * @param   entry entry to skip
2111  */
2112 void Document::SkipDocEntry(DocEntry *entry) 
2113 {
2114    SkipBytes(entry->GetLength());
2115 }
2116
2117 /**
2118  * \brief   Skips to the begining of the next Header Entry 
2119  * \warning NOT end user intended method !
2120  * @param   entry entry to skip
2121  */
2122 void Document::SkipToNextDocEntry(DocEntry *entry) 
2123 {
2124    Fp->seekg((long)(entry->GetOffset()),     std::ios_base::beg);
2125    Fp->seekg( (long)(entry->GetReadLength()), std::ios_base::cur);
2126 }
2127
2128 /**
2129  * \brief   When the length of an element value is obviously wrong (because
2130  *          the parser went Jabberwocky) one can hope improving things by
2131  *          applying some heuristics.
2132  * @param   entry entry to check
2133  * @param   foundLength fist assumption about length    
2134  */
2135 void Document::FixDocEntryFoundLength(DocEntry *entry,
2136                                       uint32_t foundLength)
2137 {
2138    entry->SetReadLength( foundLength ); // will be updated only if a bug is found        
2139    if ( foundLength == 0xffffffff)
2140    {
2141       foundLength = 0;
2142    }
2143    
2144    uint16_t gr = entry->GetGroup();
2145    uint16_t el = entry->GetElement(); 
2146      
2147    if ( foundLength % 2)
2148    {
2149       std::ostringstream s;
2150       s << "Warning : Tag with uneven length "
2151         << foundLength 
2152         <<  " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2153       dbg.Verbose(0, s.str().c_str());
2154    }
2155       
2156    //////// Fix for some naughty General Electric images.
2157    // Allthough not recent many such GE corrupted images are still present
2158    // on Creatis hard disks. Hence this fix shall remain when such images
2159    // are no longer in user (we are talking a few years, here)...
2160    // Note: XMedCom probably uses such a trick since it is able to read
2161    //       those pesky GE images ...
2162    if ( foundLength == 13)
2163    {
2164       // Only happens for this length !
2165       if ( entry->GetGroup()   != 0x0008
2166       || ( entry->GetElement() != 0x0070
2167         && entry->GetElement() != 0x0080 ) )
2168       {
2169          foundLength = 10;
2170          entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2171       }
2172    }
2173
2174    //////// Fix for some brain-dead 'Leonardo' Siemens images.
2175    // Occurence of such images is quite low (unless one leaves close to a
2176    // 'Leonardo' source. Hence, one might consider commenting out the
2177    // following fix on efficiency reasons.
2178    else if ( entry->GetGroup()   == 0x0009 
2179         && ( entry->GetElement() == 0x1113
2180           || entry->GetElement() == 0x1114 ) )
2181    {
2182       foundLength = 4;
2183       entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2184    } 
2185  
2186    else if ( entry->GetVR() == "SQ" )
2187    {
2188       foundLength = 0;      // ReadLength is unchanged 
2189    } 
2190     
2191    //////// We encountered a 'delimiter' element i.e. a tag of the form 
2192    // "fffe|xxxx" which is just a marker. Delimiters length should not be
2193    // taken into account.
2194    else if( entry->GetGroup() == 0xfffe )
2195    {    
2196      // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2197      // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2198      // causes extra troubles...
2199      if( entry->GetElement() != 0x0000 )
2200      {
2201         foundLength = 0;
2202      }
2203    } 
2204            
2205    entry->SetUsableLength(foundLength);
2206 }
2207
2208 /**
2209  * \brief   Apply some heuristics to predict whether the considered 
2210  *          element value contains/represents an integer or not.
2211  * @param   entry The element value on which to apply the predicate.
2212  * @return  The result of the heuristical predicate.
2213  */
2214 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2215 {
2216    uint16_t element = entry->GetElement();
2217    uint16_t group   = entry->GetGroup();
2218    const std::string & vr  = entry->GetVR();
2219    uint32_t length  = entry->GetLength();
2220
2221    // When we have some semantics on the element we just read, and if we
2222    // a priori know we are dealing with an integer, then we shall be
2223    // able to swap it's element value properly.
2224    if ( element == 0 )  // This is the group length of the group
2225    {  
2226       if ( length == 4 )
2227       {
2228          return true;
2229       }
2230       else 
2231       {
2232          // Allthough this should never happen, still some images have a
2233          // corrupted group length [e.g. have a glance at offset x(8336) of
2234          // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2235          // Since for dicom compliant and well behaved headers, the present
2236          // test is useless (and might even look a bit paranoid), when we
2237          // encounter such an ill-formed image, we simply display a warning
2238          // message and proceed on parsing (while crossing fingers).
2239          std::ostringstream s;
2240          long filePosition = Fp->tellg();
2241          s << "Erroneous Group Length element length  on : (" \
2242            << std::hex << group << " , " << element 
2243            << ") -before- position x(" << filePosition << ")"
2244            << "lgt : " << length;
2245          dbg.Verbose(0, "Document::IsDocEntryAnInteger", s.str().c_str() );
2246       }
2247    }
2248
2249    if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2250    {
2251       return true;
2252    }
2253    
2254    return false;
2255 }
2256
2257 /**
2258  * \brief  Find the Length till the next sequence delimiter
2259  * \warning NOT end user intended method !
2260  * @return 
2261  */
2262
2263 uint32_t Document::FindDocEntryLengthOB()
2264    throw( FormatUnexpected )
2265 {
2266    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2267    long positionOnEntry = Fp->tellg();
2268    bool foundSequenceDelimiter = false;
2269    uint32_t totalLength = 0;
2270
2271    while ( !foundSequenceDelimiter )
2272    {
2273       uint16_t group;
2274       uint16_t elem;
2275       try
2276       {
2277          group = ReadInt16();
2278          elem  = ReadInt16();   
2279       }
2280       catch ( FormatError )
2281       {
2282          throw FormatError("Document::FindDocEntryLengthOB()",
2283                            " group or element not present.");
2284       }
2285
2286       // We have to decount the group and element we just read
2287       totalLength += 4;
2288      
2289       if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2290       {
2291          dbg.Verbose(1, "Document::FindDocEntryLengthOB: neither an Item "
2292                         "tag nor a Sequence delimiter tag."); 
2293          Fp->seekg(positionOnEntry, std::ios_base::beg);
2294          throw FormatUnexpected("Document::FindDocEntryLengthOB()",
2295                                 "Neither an Item tag nor a Sequence "
2296                                 "delimiter tag.");
2297       }
2298
2299       if ( elem == 0xe0dd )
2300       {
2301          foundSequenceDelimiter = true;
2302       }
2303
2304       uint32_t itemLength = ReadInt32();
2305       // We add 4 bytes since we just read the ItemLength with ReadInt32
2306       totalLength += itemLength + 4;
2307       SkipBytes(itemLength);
2308       
2309       if ( foundSequenceDelimiter )
2310       {
2311          break;
2312       }
2313    }
2314    Fp->seekg( positionOnEntry, std::ios_base::beg);
2315    return totalLength;
2316 }
2317
2318 /**
2319  * \brief Reads a supposed to be 16 Bits integer
2320  *       (swaps it depending on processor endianity) 
2321  * @return read value
2322  */
2323 uint16_t Document::ReadInt16()
2324    throw( FormatError )
2325 {
2326    uint16_t g;
2327    Fp->read ((char*)&g, (size_t)2);
2328    if ( Fp->fail() )
2329    {
2330       throw FormatError( "Document::ReadInt16()", " file error." );
2331    }
2332    if( Fp->eof() )
2333    {
2334       throw FormatError( "Document::ReadInt16()", "EOF." );
2335    }
2336    g = SwapShort(g); 
2337    return g;
2338 }
2339
2340 /**
2341  * \brief  Reads a supposed to be 32 Bits integer
2342  *         (swaps it depending on processor endianity)  
2343  * @return read value
2344  */
2345 uint32_t Document::ReadInt32()
2346    throw( FormatError )
2347 {
2348    uint32_t g;
2349    Fp->read ((char*)&g, (size_t)4);
2350    if ( Fp->fail() )
2351    {
2352       throw FormatError( "Document::ReadInt32()", " file error." );
2353    }
2354    if( Fp->eof() )
2355    {
2356       throw FormatError( "Document::ReadInt32()", "EOF." );
2357    }
2358    g = SwapLong(g);
2359    return g;
2360 }
2361
2362 /**
2363  * \brief skips bytes inside the source file 
2364  * \warning NOT end user intended method !
2365  * @return 
2366  */
2367 void Document::SkipBytes(uint32_t nBytes)
2368 {
2369    //FIXME don't dump the returned value
2370    Fp->seekg((long)nBytes, std::ios_base::cur);
2371 }
2372
2373 /**
2374  * \brief Loads all the needed Dictionaries
2375  * \warning NOT end user intended method !   
2376  */
2377 void Document::Initialise() 
2378 {
2379    RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2380    RefShaDict = NULL;
2381    RLEInfo  = new RLEFramesInfo;
2382    JPEGInfo = new JPEGFragmentsInfo;
2383 }
2384
2385 /**
2386  * \brief   Discover what the swap code is (among little endian, big endian,
2387  *          bad little endian, bad big endian).
2388  *          sw is set
2389  * @return false when we are absolutely sure 
2390  *               it's neither ACR-NEMA nor DICOM
2391  *         true  when we hope ours assuptions are OK
2392  */
2393 bool Document::CheckSwap()
2394 {
2395    // The only guaranted way of finding the swap code is to find a
2396    // group tag since we know it's length has to be of four bytes i.e.
2397    // 0x00000004. Finding the swap code in then straigthforward. Trouble
2398    // occurs when we can't find such group...
2399    
2400    uint32_t  x = 4;  // x : for ntohs
2401    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2402    uint32_t  s32;
2403    uint16_t  s16;
2404        
2405    char deb[256]; //HEADER_LENGTH_TO_READ];
2406     
2407    // First, compare HostByteOrder and NetworkByteOrder in order to
2408    // determine if we shall need to swap bytes (i.e. the Endian type).
2409    if ( x == ntohs(x) )
2410    {
2411       net2host = true;
2412    }
2413    else
2414    {
2415       net2host = false;
2416    }
2417          
2418    // The easiest case is the one of a DICOM header, since it possesses a
2419    // file preamble where it suffice to look for the string "DICM".
2420    Fp->read(deb, HEADER_LENGTH_TO_READ);
2421    
2422    char *entCur = deb + 128;
2423    if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2424    {
2425       dbg.Verbose(1, "Document::CheckSwap:", "looks like DICOM Version3");
2426       
2427       // Next, determine the value representation (VR). Let's skip to the
2428       // first element (0002, 0000) and check there if we find "UL" 
2429       // - or "OB" if the 1st one is (0002,0001) -,
2430       // in which case we (almost) know it is explicit VR.
2431       // WARNING: if it happens to be implicit VR then what we will read
2432       // is the length of the group. If this ascii representation of this
2433       // length happens to be "UL" then we shall believe it is explicit VR.
2434       // FIXME: in order to fix the above warning, we could read the next
2435       // element value (or a couple of elements values) in order to make
2436       // sure we are not commiting a big mistake.
2437       // We need to skip :
2438       // * the 128 bytes of File Preamble (often padded with zeroes),
2439       // * the 4 bytes of "DICM" string,
2440       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2441       // i.e. a total of  136 bytes.
2442       entCur = deb + 136;
2443      
2444       // FIXME : FIXME:
2445       // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2446       // but elem 0002,0010 (Transfert Syntax) tells us the file is
2447       // *Implicit* VR.  -and it is !- 
2448       
2449       if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2450           memcmp(entCur, "OB", (size_t)2) == 0 ||
2451           memcmp(entCur, "UI", (size_t)2) == 0 ||
2452           memcmp(entCur, "CS", (size_t)2) == 0 )  // CS, to remove later
2453                                                     // when Write DCM *adds*
2454       // FIXME
2455       // Use Document::dicom_vr to test all the possibilities
2456       // instead of just checking for UL, OB and UI !? group 0000 
2457       {
2458          Filetype = ExplicitVR;
2459          dbg.Verbose(1, "Document::CheckSwap:",
2460                      "explicit Value Representation");
2461       } 
2462       else 
2463       {
2464          Filetype = ImplicitVR;
2465          dbg.Verbose(1, "Document::CheckSwap:",
2466                      "not an explicit Value Representation");
2467       }
2468       
2469       if ( net2host )
2470       {
2471          SwapCode = 4321;
2472          dbg.Verbose(1, "Document::CheckSwap:",
2473                         "HostByteOrder != NetworkByteOrder");
2474       }
2475       else 
2476       {
2477          SwapCode = 0;
2478          dbg.Verbose(1, "Document::CheckSwap:",
2479                         "HostByteOrder = NetworkByteOrder");
2480       }
2481       
2482       // Position the file position indicator at first tag (i.e.
2483       // after the file preamble and the "DICM" string).
2484       Fp->seekg(0, std::ios_base::beg);
2485       Fp->seekg ( 132L, std::ios_base::beg);
2486       return true;
2487    } // End of DicomV3
2488
2489    // Alas, this is not a DicomV3 file and whatever happens there is no file
2490    // preamble. We can reset the file position indicator to where the data
2491    // is (i.e. the beginning of the file).
2492    dbg.Verbose(1, "Document::CheckSwap:", "not a DICOM Version3 file");
2493    Fp->seekg(0, std::ios_base::beg);
2494
2495    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2496    // By clean we mean that the length of the first tag is written down.
2497    // If this is the case and since the length of the first group HAS to be
2498    // four (bytes), then determining the proper swap code is straightforward.
2499
2500    entCur = deb + 4;
2501    // We assume the array of char we are considering contains the binary
2502    // representation of a 32 bits integer. Hence the following dirty
2503    // trick :
2504    s32 = *((uint32_t *)(entCur));
2505
2506    switch( s32 )
2507    {
2508       case 0x00040000 :
2509          SwapCode = 3412;
2510          Filetype = ACR;
2511          return true;
2512       case 0x04000000 :
2513          SwapCode = 4321;
2514          Filetype = ACR;
2515          return true;
2516       case 0x00000400 :
2517          SwapCode = 2143;
2518          Filetype = ACR;
2519          return true;
2520       case 0x00000004 :
2521          SwapCode = 0;
2522          Filetype = ACR;
2523          return true;
2524       default :
2525          // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2526          // It is time for despaired wild guesses. 
2527          // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2528          //  i.e. the 'group length' element is not present :     
2529          
2530          //  check the supposed-to-be 'group number'
2531          //  in ( 0x0001 .. 0x0008 )
2532          //  to determine ' SwapCode' value .
2533          //  Only 0 or 4321 will be possible 
2534          //  (no oportunity to check for the formerly well known
2535          //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
2536          //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-) 
2537          //  the file IS NOT ACR-NEMA nor DICOM V3
2538          //  Find a trick to tell it the caller...
2539       
2540          s16 = *((uint16_t *)(deb));
2541       
2542          switch ( s16 )
2543          {
2544             case 0x0001 :
2545             case 0x0002 :
2546             case 0x0003 :
2547             case 0x0004 :
2548             case 0x0005 :
2549             case 0x0006 :
2550             case 0x0007 :
2551             case 0x0008 :
2552                SwapCode = 0;
2553                Filetype = ACR;
2554                return true;
2555             case 0x0100 :
2556             case 0x0200 :
2557             case 0x0300 :
2558             case 0x0400 :
2559             case 0x0500 :
2560             case 0x0600 :
2561             case 0x0700 :
2562             case 0x0800 :
2563                SwapCode = 4321;
2564                Filetype = ACR;
2565                return true;
2566             default :
2567                dbg.Verbose(0, "Document::CheckSwap:",
2568                      "ACR/NEMA unfound swap info (Really hopeless !)");
2569                Filetype = Unknown;
2570                return false;
2571          }
2572          // Then the only info we have is the net2host one.
2573          //if (! net2host )
2574          //   SwapCode = 0;
2575          //else
2576          //  SwapCode = 4321;
2577          //return;
2578    }
2579 }
2580
2581
2582
2583 /**
2584  * \brief Restore the unproperly loaded values i.e. the group, the element
2585  *        and the dictionary entry depending on them. 
2586  */
2587 void Document::SwitchSwapToBigEndian() 
2588 {
2589    dbg.Verbose(1, "Document::SwitchSwapToBigEndian",
2590                   "Switching to BigEndian mode.");
2591    if ( SwapCode == 0    ) 
2592    {
2593       SwapCode = 4321;
2594    }
2595    else if ( SwapCode == 4321 ) 
2596    {
2597       SwapCode = 0;
2598    }
2599    else if ( SwapCode == 3412 ) 
2600    {
2601       SwapCode = 2143;
2602    }
2603    else if ( SwapCode == 2143 )
2604    {
2605       SwapCode = 3412;
2606    }
2607 }
2608
2609 /**
2610  * \brief  during parsing, Header Elements too long are not loaded in memory 
2611  * @param newSize
2612  */
2613 void Document::SetMaxSizeLoadEntry(long newSize) 
2614 {
2615    if ( newSize < 0 )
2616    {
2617       return;
2618    }
2619    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2620    {
2621       MaxSizeLoadEntry = 0xffffffff;
2622       return;
2623    }
2624    MaxSizeLoadEntry = newSize;
2625 }
2626
2627
2628 /**
2629  * \brief Header Elements too long will not be printed
2630  * \todo  See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE 
2631  * @param newSize
2632  */
2633 void Document::SetMaxSizePrintEntry(long newSize) 
2634 {
2635    //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2636    if ( newSize < 0 )
2637    {
2638       return;
2639    }
2640    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2641    {
2642       MaxSizePrintEntry = 0xffffffff;
2643       return;
2644    }
2645    MaxSizePrintEntry = newSize;
2646 }
2647
2648
2649
2650 /**
2651  * \brief   Handle broken private tag from Philips NTSCAN
2652  *          where the endianess is being switch to BigEndian for no
2653  *          apparent reason
2654  * @return  no return
2655  */
2656 void Document::HandleBrokenEndian(uint16_t group, uint16_t elem)
2657 {
2658    // Endian reversion. Some files contain groups of tags with reversed endianess.
2659    static int reversedEndian = 0;
2660    // try to fix endian switching in the middle of headers
2661    if ((group == 0xfeff) && (elem == 0x00e0))
2662    {
2663      // start endian swap mark for group found
2664      reversedEndian++;
2665      SwitchSwapToBigEndian();
2666      // fix the tag
2667      group = 0xfffe;
2668      elem = 0xe000;
2669    } 
2670    else if ((group == 0xfffe) && (elem == 0xe00d) && reversedEndian) 
2671    {
2672      // end of reversed endian group
2673      reversedEndian--;
2674      SwitchSwapToBigEndian();
2675    }
2676
2677 }
2678
2679 /**
2680  * \brief   Read the next tag but WITHOUT loading it's value
2681  *          (read the 'Group Number', the 'Element Number',
2682  *           gets the Dict Entry
2683  *          gets the VR, gets the length, gets the offset value)
2684  * @return  On succes the newly created DocEntry, NULL on failure.      
2685  */
2686 DocEntry* Document::ReadNextDocEntry()
2687 {
2688    uint16_t group;
2689    uint16_t elem;
2690
2691    try
2692    {
2693       group = ReadInt16();
2694       elem  = ReadInt16();
2695    }
2696    catch ( FormatError e )
2697    {
2698       // We reached the EOF (or an error occured) therefore 
2699       // header parsing has to be considered as finished.
2700       //std::cout << e;
2701       return 0;
2702    }
2703
2704    HandleBrokenEndian(group, elem);
2705    DocEntry *newEntry = NewDocEntryByNumber(group, elem);
2706    FindDocEntryVR(newEntry);
2707
2708    try
2709    {
2710       FindDocEntryLength(newEntry);
2711    }
2712    catch ( FormatError e )
2713    {
2714       // Call it quits
2715       //std::cout << e;
2716       delete newEntry;
2717       return 0;
2718    }
2719
2720    newEntry->SetOffset(Fp->tellg());  
2721
2722    return newEntry;
2723 }
2724
2725
2726 /**
2727  * \brief   Generate a free TagKey i.e. a TagKey that is not present
2728  *          in the TagHt dictionary.
2729  * @param   group The generated tag must belong to this group.  
2730  * @return  The element of tag with given group which is fee.
2731  */
2732 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group) 
2733 {
2734    for (uint32_t elem = 0; elem < UINT32_MAX; elem++) 
2735    {
2736       TagKey key = DictEntry::TranslateToKey(group, elem);
2737       if (TagHT.count(key) == 0)
2738       {
2739          return elem;
2740       }
2741    }
2742    return UINT32_MAX;
2743 }
2744
2745 /**
2746  * \brief   Assuming the internal file pointer \ref Document::Fp 
2747  *          is placed at the beginning of a tag check whether this
2748  *          tag is (TestGroup, TestElement).
2749  * \warning On success the internal file pointer \ref Document::Fp
2750  *          is modified to point after the tag.
2751  *          On failure (i.e. when the tag wasn't the expected tag
2752  *          (TestGroup, TestElement) the internal file pointer
2753  *          \ref Document::Fp is restored to it's original position.
2754  * @param   testGroup   The expected group of the tag.
2755  * @param   testElement The expected Element of the tag.
2756  * @return  True on success, false otherwise.
2757  */
2758 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2759 {
2760    long positionOnEntry = Fp->tellg();
2761    long currentPosition = Fp->tellg();          // On debugging purposes
2762
2763    //// Read the Item Tag group and element, and make
2764    // sure they are what we expected:
2765    uint16_t itemTagGroup;
2766    uint16_t itemTagElement;
2767    try
2768    {
2769       itemTagGroup   = ReadInt16();
2770       itemTagElement = ReadInt16();
2771    }
2772    catch ( FormatError e )
2773    {
2774       //std::cerr << e << std::endl;
2775       return false;
2776    }
2777    if ( itemTagGroup != testGroup || itemTagElement != testElement )
2778    {
2779       std::ostringstream s;
2780       s << "   We should have found tag (";
2781       s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2782       s << "   but instead we encountered tag (";
2783       s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2784         << std::endl;
2785       s << "  at address: " << (unsigned)currentPosition << std::endl;
2786       dbg.Verbose(0, "Document::ReadItemTagLength: wrong Item Tag found:");
2787       dbg.Verbose(0, s.str().c_str());
2788       Fp->seekg(positionOnEntry, std::ios_base::beg);
2789
2790       return false;
2791    }
2792    return true;
2793 }
2794
2795 /**
2796  * \brief   Assuming the internal file pointer \ref Document::Fp 
2797  *          is placed at the beginning of a tag (TestGroup, TestElement),
2798  *          read the length associated to the Tag.
2799  * \warning On success the internal file pointer \ref Document::Fp
2800  *          is modified to point after the tag and it's length.
2801  *          On failure (i.e. when the tag wasn't the expected tag
2802  *          (TestGroup, TestElement) the internal file pointer
2803  *          \ref Document::Fp is restored to it's original position.
2804  * @param   testGroup   The expected group of the tag.
2805  * @param   testElement The expected Element of the tag.
2806  * @return  On success returns the length associated to the tag. On failure
2807  *          returns 0.
2808  */
2809 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2810 {
2811    long positionOnEntry = Fp->tellg();
2812    (void)positionOnEntry;
2813
2814    if ( !ReadTag(testGroup, testElement) )
2815    {
2816       return 0;
2817    }
2818                                                                                 
2819    //// Then read the associated Item Length
2820    long currentPosition = Fp->tellg();
2821    uint32_t itemLength  = ReadInt32();
2822    {
2823       std::ostringstream s;
2824       s << "Basic Item Length is: "
2825         << itemLength << std::endl;
2826       s << "  at address: " << (unsigned)currentPosition << std::endl;
2827       dbg.Verbose(0, "Document::ReadItemTagLength: ", s.str().c_str());
2828    }
2829    return itemLength;
2830 }
2831
2832 /**
2833  * \brief When parsing the Pixel Data of an encapsulated file, read
2834  *        the basic offset table (when present, and BTW dump it).
2835  */
2836 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2837 {
2838    //// Read the Basic Offset Table Item Tag length...
2839    uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2840
2841    // When present, read the basic offset table itself.
2842    // Notes: - since the presence of this basic offset table is optional
2843    //          we can't rely on it for the implementation, and we will simply
2844    //          trash it's content (when present).
2845    //        - still, when present, we could add some further checks on the
2846    //          lengths, but we won't bother with such fuses for the time being.
2847    if ( itemLength != 0 )
2848    {
2849       char* basicOffsetTableItemValue = new char[itemLength + 1];
2850       Fp->read(basicOffsetTableItemValue, itemLength);
2851
2852 #ifdef GDCM_DEBUG
2853       for (unsigned int i=0; i < itemLength; i += 4 )
2854       {
2855          uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2856                                               uint32_t);
2857          std::ostringstream s;
2858          s << "   Read one length: ";
2859          s << std::hex << individualLength << std::endl;
2860          dbg.Verbose(0,
2861                      "Document::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2862                      s.str().c_str());
2863       }
2864 #endif //GDCM_DEBUG
2865
2866       delete[] basicOffsetTableItemValue;
2867    }
2868 }
2869
2870 /**
2871  * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2872  *        Compute the RLE extra information and store it in \ref RLEInfo
2873  *        for later pixel retrieval usage.
2874  */
2875 void Document::ComputeRLEInfo()
2876 {
2877    TransferSyntaxType ts = GetTransferSyntax();
2878    if ( ts != RLELossless )
2879    {
2880       return;
2881    }
2882
2883    // Encoded pixel data: for the time being we are only concerned with
2884    // Jpeg or RLE Pixel data encodings.
2885    // As stated in PS 3.5-2003, section 8.2 p44:
2886    // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2887    //  value representation OB is used".
2888    // Hence we expect an OB value representation. Concerning OB VR,
2889    // the section PS 3.5-2003, section A.4.c p 58-59, states:
2890    // "For the Value Representations OB and OW, the encoding shall meet the
2891    //   following specifications depending on the Data element tag:"
2892    //   [...snip...]
2893    //    - the first item in the sequence of items before the encoded pixel
2894    //      data stream shall be basic offset table item. The basic offset table
2895    //      item value, however, is not required to be present"
2896
2897    ReadAndSkipEncapsulatedBasicOffsetTable();
2898
2899    // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2900    // Loop on the individual frame[s] and store the information
2901    // on the RLE fragments in a RLEFramesInfo.
2902    // Note: - when only a single frame is present, this is a
2903    //         classical image.
2904    //       - when more than one frame are present, then we are in 
2905    //         the case of a multi-frame image.
2906    long frameLength;
2907    while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2908    { 
2909       // Parse the RLE Header and store the corresponding RLE Segment
2910       // Offset Table information on fragments of this current Frame.
2911       // Note that the fragment pixels themselves are not loaded
2912       // (but just skipped).
2913       long frameOffset = Fp->tellg();
2914
2915       uint32_t nbRleSegments = ReadInt32();
2916       if ( nbRleSegments > 16 )
2917       {
2918          // There should be at most 15 segments (refer to RLEFrame class)
2919          dbg.Verbose(0, "Document::ComputeRLEInfo: too many segments.");
2920       }
2921  
2922       uint32_t rleSegmentOffsetTable[16];
2923       for( int k = 1; k <= 15; k++ )
2924       {
2925          rleSegmentOffsetTable[k] = ReadInt32();
2926       }
2927
2928       // Deduce from both the RLE Header and the frameLength the
2929       // fragment length, and again store this info in a
2930       // RLEFramesInfo.
2931       long rleSegmentLength[15];
2932       // skipping (not reading) RLE Segments
2933       if ( nbRleSegments > 1)
2934       {
2935          for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2936          {
2937              rleSegmentLength[k] =  rleSegmentOffsetTable[k+1]
2938                                   - rleSegmentOffsetTable[k];
2939              SkipBytes(rleSegmentLength[k]);
2940           }
2941        }
2942
2943        rleSegmentLength[nbRleSegments] = frameLength 
2944                                       - rleSegmentOffsetTable[nbRleSegments];
2945        SkipBytes(rleSegmentLength[nbRleSegments]);
2946
2947        // Store the collected info
2948        RLEFrame* newFrameInfo = new RLEFrame;
2949        newFrameInfo->NumberFragments = nbRleSegments;
2950        for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2951        {
2952           newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2953           newFrameInfo->Length[uk] = rleSegmentLength[uk];
2954        }
2955        RLEInfo->Frames.push_back( newFrameInfo );
2956    }
2957
2958    // Make sure that at the end of the item we encounter a 'Sequence
2959    // Delimiter Item':
2960    if ( !ReadTag(0xfffe, 0xe0dd) )
2961    {
2962       dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
2963       dbg.Verbose(0, "    item at end of RLE item sequence");
2964    }
2965 }
2966
2967 /**
2968  * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2969  *        Compute the jpeg extra information (fragment[s] offset[s] and
2970  *        length) and store it[them] in \ref JPEGInfo for later pixel
2971  *        retrieval usage.
2972  */
2973 void Document::ComputeJPEGFragmentInfo()
2974 {
2975    // If you need to, look for comments of ComputeRLEInfo().
2976    if ( ! IsJPEG() )
2977    {
2978       return;
2979    }
2980
2981    ReadAndSkipEncapsulatedBasicOffsetTable();
2982
2983    // Loop on the fragments[s] and store the parsed information in a
2984    // JPEGInfo.
2985    long fragmentLength;
2986    while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2987    { 
2988       long fragmentOffset = Fp->tellg();
2989
2990        // Store the collected info
2991        JPEGFragment* newFragment = new JPEGFragment;
2992        newFragment->Offset = fragmentOffset;
2993        newFragment->Length = fragmentLength;
2994        JPEGInfo->Fragments.push_back( newFragment );
2995
2996        SkipBytes( fragmentLength );
2997    }
2998
2999    // Make sure that at the end of the item we encounter a 'Sequence
3000    // Delimiter Item':
3001    if ( !ReadTag(0xfffe, 0xe0dd) )
3002    {
3003       dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3004       dbg.Verbose(0, "    item at end of JPEG item sequence");
3005    }
3006 }
3007
3008 /**
3009  * \brief Walk recursively the given \ref DocEntrySet, and feed
3010  *        the given hash table (\ref TagDocEntryHT) with all the
3011  *        \ref DocEntry (Dicom entries) encountered.
3012  *        This method does the job for \ref BuildFlatHashTable.
3013  * @param builtHT Where to collect all the \ref DocEntry encountered
3014  *        when recursively walking the given set.
3015  * @param set The structure to be traversed (recursively).
3016  */
3017 void Document::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
3018                                           DocEntrySet* set )
3019
3020    if (ElementSet* elementSet = dynamic_cast< ElementSet* > ( set ) )
3021    {
3022       TagDocEntryHT const & currentHT = elementSet->GetTagHT();
3023       for( TagDocEntryHT::const_iterator i  = currentHT.begin();
3024                                          i != currentHT.end();
3025                                        ++i)
3026       {
3027          DocEntry* entry = i->second;
3028          if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3029          {
3030             const ListSQItem& items = seqEntry->GetSQItems();
3031             for( ListSQItem::const_iterator item  = items.begin();
3032                                             item != items.end();
3033                                           ++item)
3034             {
3035                BuildFlatHashTableRecurse( builtHT, *item );
3036             }
3037             continue;
3038          }
3039          builtHT[entry->GetKey()] = entry;
3040       }
3041       return;
3042     }
3043
3044    if (SQItem* SQItemSet = dynamic_cast< SQItem* > ( set ) )
3045    {
3046       const ListDocEntry& currentList = SQItemSet->GetDocEntries();
3047       for (ListDocEntry::const_iterator i  = currentList.begin();
3048                                         i != currentList.end();
3049                                       ++i)
3050       {
3051          DocEntry* entry = *i;
3052          if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3053          {
3054             const ListSQItem& items = seqEntry->GetSQItems();
3055             for( ListSQItem::const_iterator item  = items.begin();
3056                                             item != items.end();
3057                                           ++item)
3058             {
3059                BuildFlatHashTableRecurse( builtHT, *item );
3060             }
3061             continue;
3062          }
3063          builtHT[entry->GetKey()] = entry;
3064       }
3065
3066    }
3067 }
3068
3069 /**
3070  * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3071  *        Document.
3072  *
3073  *        The structure used by a Document (through \ref ElementSet),
3074  *        in order to hold the parsed entries of a Dicom header, is a recursive
3075  *        one. This is due to the fact that the sequences (when present)
3076  *        can be nested. Additionaly, the sequence items (represented in
3077  *        gdcm as \ref SQItem) add an extra complexity to the data
3078  *        structure. Hence, a gdcm user whishing to visit all the entries of
3079  *        a Dicom header will need to dig in the gdcm internals (which
3080  *        implies exposing all the internal data structures to the API).
3081  *        In order to avoid this burden to the user, \ref BuildFlatHashTable
3082  *        recursively builds a temporary hash table, which holds all the
3083  *        Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3084  *        std::map<>).
3085  * \warning Of course there is NO integrity constrain between the 
3086  *        returned \ref TagDocEntryHT and the \ref ElementSet used
3087  *        to build it. Hence if the underlying \ref ElementSet is
3088  *        altered, then it is the caller responsability to invoke 
3089  *        \ref BuildFlatHashTable again...
3090  * @return The flat std::map<> we juste build.
3091  */
3092 TagDocEntryHT* Document::BuildFlatHashTable()
3093 {
3094    TagDocEntryHT* FlatHT = new TagDocEntryHT;
3095    BuildFlatHashTableRecurse( *FlatHT, this );
3096    return FlatHT;
3097 }
3098
3099
3100
3101 /**
3102  * \brief   Compares two documents, according to \ref DicomDir rules
3103  * \warning Does NOT work with ACR-NEMA files
3104  * \todo    Find a trick to solve the pb (use RET fields ?)
3105  * @param   document
3106  * @return  true if 'smaller'
3107  */
3108 bool Document::operator<(Document &document)
3109 {
3110    // Patient Name
3111    std::string s1 = GetEntryByNumber(0x0010,0x0010);
3112    std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3113    if(s1 < s2)
3114    {
3115       return true;
3116    }
3117    else if( s1 > s2 )
3118    {
3119       return false;
3120    }
3121    else
3122    {
3123       // Patient ID
3124       s1 = GetEntryByNumber(0x0010,0x0020);
3125       s2 = document.GetEntryByNumber(0x0010,0x0020);
3126       if ( s1 < s2 )
3127       {
3128          return true;
3129       }
3130       else if ( s1 > s2 )
3131       {
3132          return false;
3133       }
3134       else
3135       {
3136          // Study Instance UID
3137          s1 = GetEntryByNumber(0x0020,0x000d);
3138          s2 = document.GetEntryByNumber(0x0020,0x000d);
3139          if ( s1 < s2 )
3140          {
3141             return true;
3142          }
3143          else if( s1 > s2 )
3144          {
3145             return false;
3146          }
3147          else
3148          {
3149             // Serie Instance UID
3150             s1 = GetEntryByNumber(0x0020,0x000e);
3151             s2 = document.GetEntryByNumber(0x0020,0x000e);    
3152             if ( s1 < s2 )
3153             {
3154                return true;
3155             }
3156             else if( s1 > s2 )
3157             {
3158                return false;
3159             }
3160          }
3161       }
3162    }
3163    return false;
3164 }
3165
3166 } // end namespace gdcm
3167
3168 //-----------------------------------------------------------------------------