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