]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
0d32d8fc66d0c655e67a4dfbf2a5a0a4e3b87b4e
[gdcm.git] / src / gdcmDocument.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDocument.cxx,v $
5   Language:  C++
6   Date:      $Date: 2004/11/25 16:35:16 $
7   Version:   $Revision: 1.141 $
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 /*   size_t o =(size_t)docElement->GetOffset();
1060    Fp->seekg( o, std::ios_base::beg);
1061    size_t l = docElement->GetLength();
1062    uint8_t* a = new uint8_t[l];
1063    if(!a)
1064    {
1065       dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1066       return;
1067    }
1068
1069    // Read the value
1070    Fp->read((char*)a, l);
1071    if( Fp->fail() || Fp->eof() )//Fp->gcount() == 1
1072    {
1073       delete[] a;
1074       return;
1075    }
1076
1077    // Set the value to the DocEntry
1078    if( !SetEntryBinAreaByNumber( a, group, elem ) )
1079    {
1080       delete[] a;
1081       dbg.Verbose(0, "Document::LoadEntryBinArea setting failed.");
1082    }*/
1083 }
1084
1085 /**
1086  * \brief         Loads (from disk) the element content 
1087  *                when a string is not suitable
1088  * @param element  Entry whose binArea is going to be loaded
1089  */
1090 void Document::LoadEntryBinArea(BinEntry* element) 
1091 {
1092    if(element->GetBinArea())
1093       return;
1094
1095    bool openFile = !Fp;
1096    if(openFile)
1097       OpenFile();
1098
1099    size_t o =(size_t)element->GetOffset();
1100    Fp->seekg(o, std::ios_base::beg);
1101
1102    size_t l = element->GetLength();
1103    uint8_t* a = new uint8_t[l];
1104    if( !a )
1105    {
1106       dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1107       return;
1108    }
1109
1110    /// \todo check the result 
1111    Fp->read((char*)a, l);
1112    if( Fp->fail() || Fp->eof()) //Fp->gcount() == 1
1113    {
1114       delete[] a;
1115       return;
1116    }
1117
1118    element->SetBinArea(a);
1119
1120    if(openFile)
1121       CloseFile();
1122 }
1123
1124 /**
1125  * \brief   Sets a 'non string' value to a given Dicom Element
1126  * @param   area area containing the 'non string' value
1127  * @param   group     Group number of the searched Dicom Element 
1128  * @param   element Element number of the searched Dicom Element 
1129  * @return  
1130  */
1131 bool Document::SetEntryBinAreaByNumber(uint8_t* area,
1132                                        uint16_t group, uint16_t element) 
1133 {
1134    DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1135    if ( !currentEntry )
1136    {
1137       return false;
1138    }
1139
1140    if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1141    {
1142       binEntry->SetBinArea( area );
1143       return true;
1144    }
1145
1146    return false;
1147 }
1148
1149 /**
1150  * \brief   Update the entries with the shadow dictionary. 
1151  *          Only non even entries are analyzed       
1152  */
1153 void Document::UpdateShaEntries()
1154 {
1155    //DictEntry *entry;
1156    std::string vr;
1157    
1158    /// \todo TODO : still any use to explore recursively the whole structure?
1159 /*
1160    for(ListTag::iterator it=listEntries.begin();
1161        it!=listEntries.end();
1162        ++it)
1163    {
1164       // Odd group => from public dictionary
1165       if((*it)->GetGroup()%2==0)
1166          continue;
1167
1168       // Peer group => search the corresponding dict entry
1169       if(RefShaDict)
1170          entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1171       else
1172          entry=NULL;
1173
1174       if((*it)->IsImplicitVR())
1175          vr="Implicit";
1176       else
1177          vr=(*it)->GetVR();
1178
1179       (*it)->SetValue(GetDocEntryUnvalue(*it));  // to go on compiling
1180       if(entry){
1181          // Set the new entry and the new value
1182          (*it)->SetDictEntry(entry);
1183          CheckDocEntryVR(*it,vr);
1184
1185          (*it)->SetValue(GetDocEntryValue(*it));    // to go on compiling
1186  
1187       }
1188       else
1189       {
1190          // Remove precedent value transformation
1191          (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1192       }
1193    }
1194 */   
1195 }
1196
1197 /**
1198  * \brief   Searches within the Header Entries for a Dicom Element of
1199  *          a given tag.
1200  * @param   tagName name of the searched Dicom Element.
1201  * @return  Corresponding Dicom Element when it exists, and NULL
1202  *          otherwise.
1203  */
1204 DocEntry* Document::GetDocEntryByName(TagName const & tagName)
1205 {
1206    DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName); 
1207    if( !dictEntry )
1208    {
1209       return NULL;
1210    }
1211
1212   return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1213 }
1214
1215 /**
1216  * \brief  retrieves a Dicom Element (the first one) using (group, element)
1217  * \warning (group, element) IS NOT an identifier inside the Dicom Header
1218  *           if you think it's NOT UNIQUE, check the count number
1219  *           and use iterators to retrieve ALL the Dicoms Elements within
1220  *           a given couple (group, element)
1221  * @param   group Group number of the searched Dicom Element 
1222  * @param   element Element number of the searched Dicom Element 
1223  * @return  
1224  */
1225 DocEntry* Document::GetDocEntryByNumber(uint16_t group, uint16_t element) 
1226 {
1227    TagKey key = DictEntry::TranslateToKey(group, element);
1228    if ( !TagHT.count(key))
1229    {
1230       return NULL;
1231    }
1232    return TagHT.find(key)->second;
1233 }
1234
1235 /**
1236  * \brief  Same as \ref Document::GetDocEntryByNumber except it only
1237  *         returns a result when the corresponding entry is of type
1238  *         ValEntry.
1239  * @return When present, the corresponding ValEntry. 
1240  */
1241 ValEntry* Document::GetValEntryByNumber(uint16_t group, uint16_t element)
1242 {
1243    DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1244    if ( !currentEntry )
1245    {
1246       return 0;
1247    }
1248    if ( ValEntry* valEntry = dynamic_cast<ValEntry*>(currentEntry) )
1249    {
1250       return valEntry;
1251    }
1252    dbg.Verbose(0, "Document::GetValEntryByNumber: unfound ValEntry.");
1253
1254    return 0;
1255 }
1256
1257 /**
1258  * \brief         Loads the element while preserving the current
1259  *                underlying file position indicator as opposed to
1260  *                to LoadDocEntry that modifies it.
1261  * @param entry   Header Entry whose value shall be loaded. 
1262  * @return  
1263  */
1264 void Document::LoadDocEntrySafe(DocEntry * entry)
1265 {
1266    if(Fp)
1267    {
1268       long PositionOnEntry = Fp->tellg();
1269       LoadDocEntry(entry);
1270       Fp->seekg(PositionOnEntry, std::ios_base::beg);
1271    }
1272 }
1273
1274 /**
1275  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
1276  *          processor order.
1277  * @return  The properly swaped 32 bits integer.
1278  */
1279 uint32_t Document::SwapLong(uint32_t a)
1280 {
1281    switch (SwapCode)
1282    {
1283       case    0 :
1284          break;
1285       case 4321 :
1286          a=( ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000) | 
1287              ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1288          break;
1289    
1290       case 3412 :
1291          a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1292          break;
1293    
1294       case 2143 :
1295          a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
1296          break;
1297       default :
1298          //std::cout << "swapCode= " << SwapCode << std::endl;
1299          dbg.Error(" Document::SwapLong : unset swap code");
1300          a = 0;
1301    }
1302    return a;
1303
1304
1305 /**
1306  * \brief   Unswaps back the bytes of 4-byte long integer accordingly to
1307  *          processor order.
1308  * @return  The properly unswaped 32 bits integer.
1309  */
1310 uint32_t Document::UnswapLong(uint32_t a)
1311 {
1312    return SwapLong(a);
1313 }
1314
1315 /**
1316  * \brief   Swaps the bytes so they agree with the processor order
1317  * @return  The properly swaped 16 bits integer.
1318  */
1319 uint16_t Document::SwapShort(uint16_t a)
1320 {
1321    if ( SwapCode == 4321 || SwapCode == 2143 )
1322    {
1323       a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1324    }
1325    return a;
1326 }
1327
1328 /**
1329  * \brief   Unswaps the bytes so they agree with the processor order
1330  * @return  The properly unswaped 16 bits integer.
1331  */
1332 uint16_t Document::UnswapShort(uint16_t a)
1333 {
1334    return SwapShort(a);
1335 }
1336
1337 //-----------------------------------------------------------------------------
1338 // Private
1339
1340 /**
1341  * \brief   Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1342  * @return  length of the parsed set. 
1343  */ 
1344 void Document::ParseDES(DocEntrySet *set, long offset, 
1345                         long l_max, bool delim_mode)
1346 {
1347    DocEntry *newDocEntry = 0;
1348
1349    while (true)
1350    {
1351       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1352       {
1353          break;
1354       }
1355       newDocEntry = ReadNextDocEntry( );
1356       if ( !newDocEntry )
1357       {
1358          break;
1359       }
1360
1361       VRKey vr = newDocEntry->GetVR();
1362       if ( vr != "SQ" )
1363       {
1364                
1365          if ( Global::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1366          {
1367          /////////////////////// ValEntry
1368             ValEntry* newValEntry =
1369                new ValEntry( newDocEntry->GetDictEntry() ); //LEAK
1370             newValEntry->Copy( newDocEntry );
1371              
1372             // When "set" is a Document, then we are at the top of the
1373             // hierarchy and the Key is simply of the form ( group, elem )...
1374             if (Document* dummy = dynamic_cast< Document* > ( set ) )
1375             {
1376                (void)dummy;
1377                newValEntry->SetKey( newValEntry->GetKey() );
1378             }
1379             // ...but when "set" is a SQItem, we are inserting this new
1380             // valEntry in a sequence item. Hence the key has the
1381             // generalized form (refer to \ref BaseTagKey):
1382             if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1383             {
1384                newValEntry->SetKey(  parentSQItem->GetBaseTagKey()
1385                                    + newValEntry->GetKey() );
1386             }
1387              
1388             LoadDocEntry( newValEntry );
1389             bool delimitor=newValEntry->IsItemDelimitor();
1390             if( !set->AddEntry( newValEntry ) )
1391             {
1392               // If here expect big troubles
1393               delete newValEntry; //otherwise mem leak
1394             }
1395
1396             if (delimitor)
1397             {
1398                delete newDocEntry;
1399                break;
1400             }
1401             if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1402             {
1403                delete newDocEntry;
1404                break;
1405             }
1406          }
1407          else
1408          {
1409             if ( ! Global::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1410             { 
1411                 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1412                 dbg.Verbose(0, "Document::ParseDES: neither Valentry, "
1413                                "nor BinEntry. Probably unknown VR.");
1414             }
1415
1416          //////////////////// BinEntry or UNKOWN VR:
1417             BinEntry* newBinEntry = new BinEntry( newDocEntry );  //LEAK
1418
1419             // When "this" is a Document the Key is simply of the
1420             // form ( group, elem )...
1421             if (Document* dummy = dynamic_cast< Document* > ( set ) )
1422             {
1423                (void)dummy;
1424                newBinEntry->SetKey( newBinEntry->GetKey() );
1425             }
1426             // but when "this" is a SQItem, we are inserting this new
1427             // valEntry in a sequence item, and the kay has the
1428             // generalized form (refer to \ref BaseTagKey):
1429             if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1430             {
1431                newBinEntry->SetKey(  parentSQItem->GetBaseTagKey()
1432                                    + newBinEntry->GetKey() );
1433             }
1434
1435             LoadDocEntry( newBinEntry );
1436             if( !set->AddEntry( newBinEntry ) )
1437             {
1438               //Expect big troubles if here
1439               delete newBinEntry;
1440             }
1441          }
1442
1443          if (    ( newDocEntry->GetGroup()   == 0x7fe0 )
1444               && ( newDocEntry->GetElement() == 0x0010 ) )
1445          {
1446              TransferSyntaxType ts = GetTransferSyntax();
1447              if ( ts == RLELossless ) 
1448              {
1449                 long PositionOnEntry = Fp->tellg();
1450                 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1451                 ComputeRLEInfo();
1452                 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1453              }
1454              else if ( IsJPEG() )
1455              {
1456                 long PositionOnEntry = Fp->tellg();
1457                 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1458                 ComputeJPEGFragmentInfo();
1459                 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1460              }
1461          }
1462     
1463          // Just to make sure we are at the beginning of next entry.
1464          SkipToNextDocEntry(newDocEntry);
1465          //delete newDocEntry;
1466       }
1467       else
1468       {
1469          // VR = "SQ"
1470          unsigned long l = newDocEntry->GetReadLength();            
1471          if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1472          {
1473             if ( l == 0xffffffff )
1474             {
1475               delim_mode = true;
1476             }
1477             else
1478             {
1479               delim_mode = false;
1480             }
1481          }
1482          // no other way to create it ...
1483          SeqEntry* newSeqEntry =
1484             new SeqEntry( newDocEntry->GetDictEntry() );
1485          newSeqEntry->Copy( newDocEntry );
1486          newSeqEntry->SetDelimitorMode( delim_mode );
1487
1488          // At the top of the hierarchy, stands a Document. When "set"
1489          // is a Document, then we are building the first depth level.
1490          // Hence the SeqEntry we are building simply has a depth
1491          // level of one:
1492          if (Document* dummy = dynamic_cast< Document* > ( set ) )
1493          {
1494             (void)dummy;
1495             newSeqEntry->SetDepthLevel( 1 );
1496             newSeqEntry->SetKey( newSeqEntry->GetKey() );
1497          }
1498          // But when "set" is allready a SQItem, we are building a nested
1499          // sequence, and hence the depth level of the new SeqEntry
1500          // we are building, is one level deeper:
1501          if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1502          {
1503             newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1504             newSeqEntry->SetKey(  parentSQItem->GetBaseTagKey()
1505                                 + newSeqEntry->GetKey() );
1506          }
1507
1508          if ( l != 0 )
1509          {  // Don't try to parse zero-length sequences
1510             ParseSQ( newSeqEntry, 
1511                      newDocEntry->GetOffset(),
1512                      l, delim_mode);
1513          }
1514          set->AddEntry( newSeqEntry );
1515          if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1516          {
1517             delete newDocEntry;
1518             break;
1519          }
1520       }
1521       delete newDocEntry;
1522    }
1523 }
1524
1525 /**
1526  * \brief   Parses a Sequence ( SeqEntry after SeqEntry)
1527  * @return  parsed length for this level
1528  */ 
1529 void Document::ParseSQ( SeqEntry* seqEntry,
1530                         long offset, long l_max, bool delim_mode)
1531 {
1532    int SQItemNumber = 0;
1533    bool dlm_mod;
1534
1535    while (true)
1536    {
1537       DocEntry* newDocEntry = ReadNextDocEntry();   
1538       if ( !newDocEntry )
1539       {
1540          // FIXME Should warn user
1541          break;
1542       }
1543       if( delim_mode )
1544       {
1545          if ( newDocEntry->IsSequenceDelimitor() )
1546          {
1547             seqEntry->SetSequenceDelimitationItem( newDocEntry ); 
1548             break;
1549          }
1550       }
1551       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1552       {
1553          delete newDocEntry;
1554          break;
1555       }
1556
1557       SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1558       std::ostringstream newBase;
1559       newBase << seqEntry->GetKey()
1560               << "/"
1561               << SQItemNumber
1562               << "#";
1563       itemSQ->SetBaseTagKey( newBase.str() );
1564       unsigned int l = newDocEntry->GetReadLength();
1565       
1566       if ( l == 0xffffffff )
1567       {
1568          dlm_mod = true;
1569       }
1570       else
1571       {
1572          dlm_mod = false;
1573       }
1574    
1575       ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1576       delete newDocEntry;
1577       
1578       seqEntry->AddEntry( itemSQ, SQItemNumber ); 
1579       SQItemNumber++;
1580       if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1581       {
1582          break;
1583       }
1584    }
1585 }
1586
1587 /**
1588  * \brief         Loads the element content if its length doesn't exceed
1589  *                the value specified with Document::SetMaxSizeLoadEntry()
1590  * @param         entry Header Entry (Dicom Element) to be dealt with
1591  */
1592 void Document::LoadDocEntry(DocEntry* entry)
1593 {
1594    uint16_t group  = entry->GetGroup();
1595    std::string  vr = entry->GetVR();
1596    uint32_t length = entry->GetLength();
1597
1598    Fp->seekg((long)entry->GetOffset(), std::ios_base::beg);
1599
1600    // A SeQuence "contains" a set of Elements.  
1601    //          (fffe e000) tells us an Element is beginning
1602    //          (fffe e00d) tells us an Element just ended
1603    //          (fffe e0dd) tells us the current SeQuence just ended
1604    if( group == 0xfffe )
1605    {
1606       // NO more value field for SQ !
1607       return;
1608    }
1609
1610    // When the length is zero things are easy:
1611    if ( length == 0 )
1612    {
1613       ((ValEntry *)entry)->SetValue("");
1614       return;
1615    }
1616
1617    // The elements whose length is bigger than the specified upper bound
1618    // are not loaded. Instead we leave a short notice of the offset of
1619    // the element content and it's length.
1620
1621    std::ostringstream s;
1622    if (length > MaxSizeLoadEntry)
1623    {
1624       if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1625       {  
1626          //s << "gdcm::NotLoaded (BinEntry)";
1627          s << GDCM_NOTLOADED;
1628          s << " Address:" << (long)entry->GetOffset();
1629          s << " Length:"  << entry->GetLength();
1630          s << " x(" << std::hex << entry->GetLength() << ")";
1631          binEntryPtr->SetValue(s.str());
1632       }
1633       // Be carefull : a BinEntry IS_A ValEntry ... 
1634       else if (ValEntry* valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1635       {
1636         // s << "gdcm::NotLoaded. (ValEntry)";
1637          s << GDCM_NOTLOADED;  
1638          s << " Address:" << (long)entry->GetOffset();
1639          s << " Length:"  << entry->GetLength();
1640          s << " x(" << std::hex << entry->GetLength() << ")";
1641          valEntryPtr->SetValue(s.str());
1642       }
1643       else
1644       {
1645          // fusible
1646          std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1647                   << "nor a ValEntry ?! Should never print that !" << std::endl;
1648       }
1649
1650       // to be sure we are at the end of the value ...
1651       Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1652                 std::ios_base::beg);
1653       return;
1654    }
1655
1656    // When we find a BinEntry not very much can be done :
1657    if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1658    {
1659       s << GDCM_BINLOADED;
1660       binEntryPtr->SetValue(s.str());
1661       LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1662       return;
1663    }
1664     
1665    /// \todo Any compacter code suggested (?)
1666    if ( IsDocEntryAnInteger(entry) )
1667    {   
1668       uint32_t NewInt;
1669       int nbInt;
1670       // When short integer(s) are expected, read and convert the following 
1671       // n *two characters properly i.e. consider them as short integers as
1672       // opposed to strings.
1673       // Elements with Value Multiplicity > 1
1674       // contain a set of integers (not a single one)       
1675       if (vr == "US" || vr == "SS")
1676       {
1677          nbInt = length / 2;
1678          NewInt = ReadInt16();
1679          s << NewInt;
1680          if (nbInt > 1)
1681          {
1682             for (int i=1; i < nbInt; i++)
1683             {
1684                s << '\\';
1685                NewInt = ReadInt16();
1686                s << NewInt;
1687             }
1688          }
1689       }
1690       // See above comment on multiple integers (mutatis mutandis).
1691       else if (vr == "UL" || vr == "SL")
1692       {
1693          nbInt = length / 4;
1694          NewInt = ReadInt32();
1695          s << NewInt;
1696          if (nbInt > 1)
1697          {
1698             for (int i=1; i < nbInt; i++)
1699             {
1700                s << '\\';
1701                NewInt = ReadInt32();
1702                s << NewInt;
1703             }
1704          }
1705       }
1706 #ifdef GDCM_NO_ANSI_STRING_STREAM
1707       s << std::ends; // to avoid oddities on Solaris
1708 #endif //GDCM_NO_ANSI_STRING_STREAM
1709
1710       ((ValEntry *)entry)->SetValue(s.str());
1711       return;
1712    }
1713    
1714   // FIXME: We need an additional byte for storing \0 that is not on disk
1715    char *str = new char[length+1];
1716    Fp->read(str, (size_t)length);
1717    str[length] = '\0'; //this is only useful when length is odd
1718    // Special DicomString call to properly handle \0 and even length
1719    std::string newValue;
1720    if( length % 2 )
1721    {
1722       newValue = Util::DicomString(str, length+1);
1723       //dbg.Verbose(0, "Warning: bad length: ", length );
1724       dbg.Verbose(0, "For string :",  newValue.c_str()); 
1725       // Since we change the length of string update it length
1726       entry->SetReadLength(length+1);
1727    }
1728    else
1729    {
1730       newValue = Util::DicomString(str, length);
1731    }
1732    delete[] str;
1733
1734    if ( ValEntry* valEntry = dynamic_cast<ValEntry* >(entry) )
1735    {
1736       if ( Fp->fail() || Fp->eof())//Fp->gcount() == 1
1737       {
1738          dbg.Verbose(1, "Document::LoadDocEntry",
1739                         "unread element value");
1740          valEntry->SetValue(GDCM_UNREAD);
1741          return;
1742       }
1743
1744       if( vr == "UI" )
1745       {
1746          // Because of correspondance with the VR dic
1747          valEntry->SetValue(newValue);
1748       }
1749       else
1750       {
1751          valEntry->SetValue(newValue);
1752       }
1753    }
1754    else
1755    {
1756       dbg.Error(true, "Document::LoadDocEntry"
1757                       "Should have a ValEntry, here !");
1758    }
1759 }
1760
1761
1762 /**
1763  * \brief  Find the value Length of the passed Header Entry
1764  * @param  entry Header Entry whose length of the value shall be loaded. 
1765  */
1766 void Document::FindDocEntryLength( DocEntry *entry )
1767    throw ( FormatError )
1768 {
1769    uint16_t element = entry->GetElement();
1770    std::string  vr  = entry->GetVR();
1771    uint16_t length16;       
1772    
1773    if ( Filetype == ExplicitVR && !entry->IsImplicitVR() ) 
1774    {
1775       if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" ) 
1776       {
1777          // The following reserved two bytes (see PS 3.5-2003, section
1778          // "7.1.2 Data element structure with explicit vr", p 27) must be
1779          // skipped before proceeding on reading the length on 4 bytes.
1780          Fp->seekg( 2L, std::ios_base::cur);
1781          uint32_t length32 = ReadInt32();
1782
1783          if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff ) 
1784          {
1785             uint32_t lengthOB;
1786             try 
1787             {
1788                /// \todo rename that to FindDocEntryLengthOBOrOW since
1789                ///       the above test is on both OB and OW...
1790                lengthOB = FindDocEntryLengthOB();
1791             }
1792             catch ( FormatUnexpected )
1793             {
1794                // Computing the length failed (this happens with broken
1795                // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1796                // chance to get the pixels by deciding the element goes
1797                // until the end of the file. Hence we artificially fix the
1798                // the length and proceed.
1799                long currentPosition = Fp->tellg();
1800                Fp->seekg(0L,std::ios_base::end);
1801                long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1802                Fp->seekg(currentPosition, std::ios_base::beg);
1803                entry->SetLength(lengthUntilEOF);
1804                return;
1805             }
1806             entry->SetLength(lengthOB);
1807             return;
1808          }
1809          FixDocEntryFoundLength(entry, length32); 
1810          return;
1811       }
1812
1813       // Length is encoded on 2 bytes.
1814       length16 = ReadInt16();
1815       
1816       // We can tell the current file is encoded in big endian (like
1817       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1818       // and it's value is the one of the encoding of a big endian file.
1819       // In order to deal with such big endian encoded files, we have
1820       // (at least) two strategies:
1821       // * when we load the "Transfer Syntax" tag with value of big endian
1822       //   encoding, we raise the proper flags. Then we wait for the end
1823       //   of the META group (0x0002) among which is "Transfer Syntax",
1824       //   before switching the swap code to big endian. We have to postpone
1825       //   the switching of the swap code since the META group is fully encoded
1826       //   in little endian, and big endian coding only starts at the next
1827       //   group. The corresponding code can be hard to analyse and adds
1828       //   many additional unnecessary tests for regular tags.
1829       // * the second strategy consists in waiting for trouble, that shall
1830       //   appear when we find the first group with big endian encoding. This
1831       //   is easy to detect since the length of a "Group Length" tag (the
1832       //   ones with zero as element number) has to be of 4 (0x0004). When we
1833       //   encounter 1024 (0x0400) chances are the encoding changed and we
1834       //   found a group with big endian encoding.
1835       // We shall use this second strategy. In order to make sure that we
1836       // can interpret the presence of an apparently big endian encoded
1837       // length of a "Group Length" without committing a big mistake, we
1838       // add an additional check: we look in the already parsed elements
1839       // for the presence of a "Transfer Syntax" whose value has to be "big
1840       // endian encoding". When this is the case, chances are we have got our
1841       // hands on a big endian encoded file: we switch the swap code to
1842       // big endian and proceed...
1843       if ( element  == 0x0000 && length16 == 0x0400 ) 
1844       {
1845          TransferSyntaxType ts = GetTransferSyntax();
1846          if ( ts != ExplicitVRBigEndian ) 
1847          {
1848             throw FormatError( "Document::FindDocEntryLength()",
1849                                " not explicit VR." );
1850             return;
1851          }
1852          length16 = 4;
1853          SwitchSwapToBigEndian();
1854          // Restore the unproperly loaded values i.e. the group, the element
1855          // and the dictionary entry depending on them.
1856          uint16_t correctGroup = SwapShort( entry->GetGroup() );
1857          uint16_t correctElem  = SwapShort( entry->GetElement() );
1858          DictEntry* newTag = GetDictEntryByNumber( correctGroup,
1859                                                        correctElem );
1860          if ( !newTag )
1861          {
1862             // This correct tag is not in the dictionary. Create a new one.
1863             newTag = NewVirtualDictEntry(correctGroup, correctElem);
1864          }
1865          // FIXME this can create a memory leaks on the old entry that be
1866          // left unreferenced.
1867          entry->SetDictEntry( newTag );
1868       }
1869        
1870       // Heuristic: well, some files are really ill-formed.
1871       if ( length16 == 0xffff) 
1872       {
1873          // 0xffff means that we deal with 'Unknown Length' Sequence  
1874          length16 = 0;
1875       }
1876       FixDocEntryFoundLength( entry, (uint32_t)length16 );
1877       return;
1878    }
1879    else
1880    {
1881       // Either implicit VR or a non DICOM conformal (see note below) explicit
1882       // VR that ommited the VR of (at least) this element. Farts happen.
1883       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1884       // on Data elements "Implicit and Explicit VR Data Elements shall
1885       // not coexist in a Data Set and Data Sets nested within it".]
1886       // Length is on 4 bytes.
1887       
1888       FixDocEntryFoundLength( entry, ReadInt32() );
1889       return;
1890    }
1891 }
1892
1893 /**
1894  * \brief     Find the Value Representation of the current Dicom Element.
1895  * @param     entry
1896  */
1897 void Document::FindDocEntryVR( DocEntry *entry )
1898 {
1899    if ( Filetype != ExplicitVR )
1900    {
1901       return;
1902    }
1903
1904    char vr[3];
1905
1906    long positionOnEntry = Fp->tellg();
1907    // Warning: we believe this is explicit VR (Value Representation) because
1908    // we used a heuristic that found "UL" in the first tag. Alas this
1909    // doesn't guarantee that all the tags will be in explicit VR. In some
1910    // cases (see e-film filtered files) one finds implicit VR tags mixed
1911    // within an explicit VR file. Hence we make sure the present tag
1912    // is in explicit VR and try to fix things if it happens not to be
1913    // the case.
1914    
1915    Fp->read (vr, (size_t)2);
1916    vr[2] = 0;
1917
1918    if( !CheckDocEntryVR(entry, vr) )
1919    {
1920       Fp->seekg(positionOnEntry, std::ios_base::beg);
1921       // When this element is known in the dictionary we shall use, e.g. for
1922       // the semantics (see the usage of IsAnInteger), the VR proposed by the
1923       // dictionary entry. Still we have to flag the element as implicit since
1924       // we know now our assumption on expliciteness is not furfilled.
1925       // avoid  .
1926       if ( entry->IsVRUnknown() )
1927       {
1928          entry->SetVR("Implicit");
1929       }
1930       entry->SetImplicitVR();
1931    }
1932 }
1933
1934 /**
1935  * \brief     Check the correspondance between the VR of the header entry
1936  *            and the taken VR. If they are different, the header entry is 
1937  *            updated with the new VR.
1938  * @param     entry Header Entry to check
1939  * @param     vr    Dicom Value Representation
1940  * @return    false if the VR is incorrect of if the VR isn't referenced
1941  *            otherwise, it returns true
1942 */
1943 bool Document::CheckDocEntryVR(DocEntry *entry, VRKey vr)
1944 {
1945    std::string msg;
1946    bool realExplicit = true;
1947
1948    // Assume we are reading a falsely explicit VR file i.e. we reached
1949    // a tag where we expect reading a VR but are in fact we read the
1950    // first to bytes of the length. Then we will interogate (through find)
1951    // the dicom_vr dictionary with oddities like "\004\0" which crashes
1952    // both GCC and VC++ implementations of the STL map. Hence when the
1953    // expected VR read happens to be non-ascii characters we consider
1954    // we hit falsely explicit VR tag.
1955
1956    if ( !isalpha((unsigned char)vr[0]) && !isalpha((unsigned char)vr[1]) )
1957    {
1958       realExplicit = false;
1959    }
1960
1961    // CLEANME searching the dicom_vr at each occurence is expensive.
1962    // PostPone this test in an optional integrity check at the end
1963    // of parsing or only in debug mode.
1964    if ( realExplicit && !Global::GetVR()->Count(vr) )
1965    {
1966       realExplicit = false;
1967    }
1968
1969    if ( !realExplicit ) 
1970    {
1971       // We thought this was explicit VR, but we end up with an
1972       // implicit VR tag. Let's backtrack.   
1973       msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n", 
1974                     entry->GetGroup(), entry->GetElement());
1975       dbg.Verbose(1, "Document::FindVR: ", msg.c_str());
1976
1977       if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1978       {
1979          // Group length is UL !
1980          DictEntry* newEntry = NewVirtualDictEntry(
1981                                    entry->GetGroup(), entry->GetElement(),
1982                                    "UL", "FIXME", "Group Length");
1983          entry->SetDictEntry( newEntry );
1984       }
1985       return false;
1986    }
1987
1988    if ( entry->IsVRUnknown() )
1989    {
1990       // When not a dictionary entry, we can safely overwrite the VR.
1991       if( entry->GetElement() == 0x0000 )
1992       {
1993          // Group length is UL !
1994          entry->SetVR("UL");
1995       }
1996       else
1997       {
1998          entry->SetVR(vr);
1999       }
2000    }
2001    else if ( entry->GetVR() != vr ) 
2002    {
2003       // The VR present in the file and the dictionary disagree. We assume
2004       // the file writer knew best and use the VR of the file. Since it would
2005       // be unwise to overwrite the VR of a dictionary (since it would
2006       // compromise it's next user), we need to clone the actual DictEntry
2007       // and change the VR for the read one.
2008       DictEntry* newEntry = NewVirtualDictEntry(
2009                                 entry->GetGroup(), entry->GetElement(),
2010                                 vr, "FIXME", entry->GetName());
2011       entry->SetDictEntry(newEntry);
2012    }
2013
2014    return true; 
2015 }
2016
2017 /**
2018  * \brief   Get the transformed value of the header entry. The VR value 
2019  *          is used to define the transformation to operate on the value
2020  * \warning NOT end user intended method !
2021  * @param   entry entry to tranform
2022  * @return  Transformed entry value
2023  */
2024 std::string Document::GetDocEntryValue(DocEntry *entry)
2025 {
2026    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2027    {
2028       std::string val = ((ValEntry *)entry)->GetValue();
2029       std::string vr  = entry->GetVR();
2030       uint32_t length = entry->GetLength();
2031       std::ostringstream s;
2032       int nbInt;
2033
2034       // When short integer(s) are expected, read and convert the following 
2035       // n * 2 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 short integers (not a single one) 
2040    
2041       if( vr == "US" || vr == "SS" )
2042       {
2043          uint16_t newInt16;
2044
2045          nbInt = length / 2;
2046          for (int i=0; i < nbInt; i++) 
2047          {
2048             if( i != 0 )
2049             {
2050                s << '\\';
2051             }
2052             newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2053             newInt16 = SwapShort( newInt16 );
2054             s << newInt16;
2055          }
2056       }
2057
2058       // When integer(s) are expected, read and convert the following 
2059       // n * 4 bytes properly i.e. as a multivaluated strings
2060       // (each single value is separated fromthe next one by '\'
2061       // as usual for standard multivaluated filels
2062       // Elements with Value Multiplicity > 1
2063       // contain a set of integers (not a single one) 
2064       else if( vr == "UL" || vr == "SL" )
2065       {
2066          uint32_t newInt32;
2067
2068          nbInt = length / 4;
2069          for (int i=0; i < nbInt; i++) 
2070          {
2071             if( i != 0)
2072             {
2073                s << '\\';
2074             }
2075             newInt32 = ( val[4*i+0] & 0xFF )
2076                     + (( val[4*i+1] & 0xFF ) <<  8 )
2077                     + (( val[4*i+2] & 0xFF ) << 16 )
2078                     + (( val[4*i+3] & 0xFF ) << 24 );
2079             newInt32 = SwapLong( newInt32 );
2080             s << newInt32;
2081          }
2082       }
2083 #ifdef GDCM_NO_ANSI_STRING_STREAM
2084       s << std::ends; // to avoid oddities on Solaris
2085 #endif //GDCM_NO_ANSI_STRING_STREAM
2086       return s.str();
2087    }
2088
2089    return ((ValEntry *)entry)->GetValue();
2090 }
2091
2092 /**
2093  * \brief   Get the reverse transformed value of the header entry. The VR 
2094  *          value is used to define the reverse transformation to operate on
2095  *          the value
2096  * \warning NOT end user intended method !
2097  * @param   entry Entry to reverse transform
2098  * @return  Reverse transformed entry value
2099  */
2100 std::string Document::GetDocEntryUnvalue(DocEntry* entry)
2101 {
2102    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2103    {
2104       std::string vr = entry->GetVR();
2105       std::vector<std::string> tokens;
2106       std::ostringstream s;
2107
2108       if ( vr == "US" || vr == "SS" ) 
2109       {
2110          uint16_t newInt16;
2111
2112          tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2113          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2114          for (unsigned int i=0; i<tokens.size(); i++) 
2115          {
2116             newInt16 = atoi(tokens[i].c_str());
2117             s << (  newInt16        & 0xFF ) 
2118               << (( newInt16 >> 8 ) & 0xFF );
2119          }
2120          tokens.clear();
2121       }
2122       if ( vr == "UL" || vr == "SL")
2123       {
2124          uint32_t newInt32;
2125
2126          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2127          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2128          for (unsigned int i=0; i<tokens.size();i++) 
2129          {
2130             newInt32 = atoi(tokens[i].c_str());
2131             s << (char)(  newInt32         & 0xFF ) 
2132               << (char)(( newInt32 >>  8 ) & 0xFF )
2133               << (char)(( newInt32 >> 16 ) & 0xFF )
2134               << (char)(( newInt32 >> 24 ) & 0xFF );
2135          }
2136          tokens.clear();
2137       }
2138
2139 #ifdef GDCM_NO_ANSI_STRING_STREAM
2140       s << std::ends; // to avoid oddities on Solaris
2141 #endif //GDCM_NO_ANSI_STRING_STREAM
2142       return s.str();
2143    }
2144
2145    return ((ValEntry *)entry)->GetValue();
2146 }
2147
2148 /**
2149  * \brief   Skip a given Header Entry 
2150  * \warning NOT end user intended method !
2151  * @param   entry entry to skip
2152  */
2153 void Document::SkipDocEntry(DocEntry *entry) 
2154 {
2155    SkipBytes(entry->GetLength());
2156 }
2157
2158 /**
2159  * \brief   Skips to the begining of the next Header Entry 
2160  * \warning NOT end user intended method !
2161  * @param   entry entry to skip
2162  */
2163 void Document::SkipToNextDocEntry(DocEntry *entry) 
2164 {
2165    Fp->seekg((long)(entry->GetOffset()),     std::ios_base::beg);
2166    Fp->seekg( (long)(entry->GetReadLength()), std::ios_base::cur);
2167 }
2168
2169 /**
2170  * \brief   When the length of an element value is obviously wrong (because
2171  *          the parser went Jabberwocky) one can hope improving things by
2172  *          applying some heuristics.
2173  * @param   entry entry to check
2174  * @param   foundLength fist assumption about length    
2175  */
2176 void Document::FixDocEntryFoundLength(DocEntry *entry,
2177                                       uint32_t foundLength)
2178 {
2179    entry->SetReadLength( foundLength ); // will be updated only if a bug is found        
2180    if ( foundLength == 0xffffffff)
2181    {
2182       foundLength = 0;
2183    }
2184    
2185    uint16_t gr = entry->GetGroup();
2186    uint16_t el = entry->GetElement(); 
2187      
2188    if ( foundLength % 2)
2189    {
2190       std::ostringstream s;
2191       s << "Warning : Tag with uneven length "
2192         << foundLength 
2193         <<  " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2194       dbg.Verbose(0, s.str().c_str());
2195    }
2196       
2197    //////// Fix for some naughty General Electric images.
2198    // Allthough not recent many such GE corrupted images are still present
2199    // on Creatis hard disks. Hence this fix shall remain when such images
2200    // are no longer in user (we are talking a few years, here)...
2201    // Note: XMedCom probably uses such a trick since it is able to read
2202    //       those pesky GE images ...
2203    if ( foundLength == 13)
2204    {
2205       // Only happens for this length !
2206       if ( entry->GetGroup()   != 0x0008
2207       || ( entry->GetElement() != 0x0070
2208         && entry->GetElement() != 0x0080 ) )
2209       {
2210          foundLength = 10;
2211          entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2212       }
2213    }
2214
2215    //////// Fix for some brain-dead 'Leonardo' Siemens images.
2216    // Occurence of such images is quite low (unless one leaves close to a
2217    // 'Leonardo' source. Hence, one might consider commenting out the
2218    // following fix on efficiency reasons.
2219    else if ( entry->GetGroup()   == 0x0009 
2220         && ( entry->GetElement() == 0x1113
2221           || entry->GetElement() == 0x1114 ) )
2222    {
2223       foundLength = 4;
2224       entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2225    } 
2226  
2227    else if ( entry->GetVR() == "SQ" )
2228    {
2229       foundLength = 0;      // ReadLength is unchanged 
2230    } 
2231     
2232    //////// We encountered a 'delimiter' element i.e. a tag of the form 
2233    // "fffe|xxxx" which is just a marker. Delimiters length should not be
2234    // taken into account.
2235    else if( entry->GetGroup() == 0xfffe )
2236    {    
2237      // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2238      // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2239      // causes extra troubles...
2240      if( entry->GetElement() != 0x0000 )
2241      {
2242         foundLength = 0;
2243      }
2244    } 
2245            
2246    entry->SetUsableLength(foundLength);
2247 }
2248
2249 /**
2250  * \brief   Apply some heuristics to predict whether the considered 
2251  *          element value contains/represents an integer or not.
2252  * @param   entry The element value on which to apply the predicate.
2253  * @return  The result of the heuristical predicate.
2254  */
2255 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2256 {
2257    uint16_t element = entry->GetElement();
2258    uint16_t group   = entry->GetGroup();
2259    const std::string & vr  = entry->GetVR();
2260    uint32_t length  = entry->GetLength();
2261
2262    // When we have some semantics on the element we just read, and if we
2263    // a priori know we are dealing with an integer, then we shall be
2264    // able to swap it's element value properly.
2265    if ( element == 0 )  // This is the group length of the group
2266    {  
2267       if ( length == 4 )
2268       {
2269          return true;
2270       }
2271       else 
2272       {
2273          // Allthough this should never happen, still some images have a
2274          // corrupted group length [e.g. have a glance at offset x(8336) of
2275          // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2276          // Since for dicom compliant and well behaved headers, the present
2277          // test is useless (and might even look a bit paranoid), when we
2278          // encounter such an ill-formed image, we simply display a warning
2279          // message and proceed on parsing (while crossing fingers).
2280          std::ostringstream s;
2281          long filePosition = Fp->tellg();
2282          s << "Erroneous Group Length element length  on : (" \
2283            << std::hex << group << " , " << element 
2284            << ") -before- position x(" << filePosition << ")"
2285            << "lgt : " << length;
2286          dbg.Verbose(0, "Document::IsDocEntryAnInteger", s.str().c_str() );
2287       }
2288    }
2289
2290    if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2291    {
2292       return true;
2293    }
2294    
2295    return false;
2296 }
2297
2298 /**
2299  * \brief  Find the Length till the next sequence delimiter
2300  * \warning NOT end user intended method !
2301  * @return 
2302  */
2303
2304 uint32_t Document::FindDocEntryLengthOB()
2305    throw( FormatUnexpected )
2306 {
2307    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2308    long positionOnEntry = Fp->tellg();
2309    bool foundSequenceDelimiter = false;
2310    uint32_t totalLength = 0;
2311
2312    while ( !foundSequenceDelimiter )
2313    {
2314       uint16_t group;
2315       uint16_t elem;
2316       try
2317       {
2318          group = ReadInt16();
2319          elem  = ReadInt16();   
2320       }
2321       catch ( FormatError )
2322       {
2323          throw FormatError("Document::FindDocEntryLengthOB()",
2324                            " group or element not present.");
2325       }
2326
2327       // We have to decount the group and element we just read
2328       totalLength += 4;
2329      
2330       if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2331       {
2332          dbg.Verbose(1, "Document::FindDocEntryLengthOB: neither an Item "
2333                         "tag nor a Sequence delimiter tag."); 
2334          Fp->seekg(positionOnEntry, std::ios_base::beg);
2335          throw FormatUnexpected("Document::FindDocEntryLengthOB()",
2336                                 "Neither an Item tag nor a Sequence "
2337                                 "delimiter tag.");
2338       }
2339
2340       if ( elem == 0xe0dd )
2341       {
2342          foundSequenceDelimiter = true;
2343       }
2344
2345       uint32_t itemLength = ReadInt32();
2346       // We add 4 bytes since we just read the ItemLength with ReadInt32
2347       totalLength += itemLength + 4;
2348       SkipBytes(itemLength);
2349       
2350       if ( foundSequenceDelimiter )
2351       {
2352          break;
2353       }
2354    }
2355    Fp->seekg( positionOnEntry, std::ios_base::beg);
2356    return totalLength;
2357 }
2358
2359 /**
2360  * \brief Reads a supposed to be 16 Bits integer
2361  *       (swaps it depending on processor endianity) 
2362  * @return read value
2363  */
2364 uint16_t Document::ReadInt16()
2365    throw( FormatError )
2366 {
2367    uint16_t g;
2368    Fp->read ((char*)&g, (size_t)2);
2369    if ( Fp->fail() )
2370    {
2371       throw FormatError( "Document::ReadInt16()", " file error." );
2372    }
2373    if( Fp->eof() )
2374    {
2375       throw FormatError( "Document::ReadInt16()", "EOF." );
2376    }
2377    g = SwapShort(g); 
2378    return g;
2379 }
2380
2381 /**
2382  * \brief  Reads a supposed to be 32 Bits integer
2383  *         (swaps it depending on processor endianity)  
2384  * @return read value
2385  */
2386 uint32_t Document::ReadInt32()
2387    throw( FormatError )
2388 {
2389    uint32_t g;
2390    Fp->read ((char*)&g, (size_t)4);
2391    if ( Fp->fail() )
2392    {
2393       throw FormatError( "Document::ReadInt32()", " file error." );
2394    }
2395    if( Fp->eof() )
2396    {
2397       throw FormatError( "Document::ReadInt32()", "EOF." );
2398    }
2399    g = SwapLong(g);
2400    return g;
2401 }
2402
2403 /**
2404  * \brief skips bytes inside the source file 
2405  * \warning NOT end user intended method !
2406  * @return 
2407  */
2408 void Document::SkipBytes(uint32_t nBytes)
2409 {
2410    //FIXME don't dump the returned value
2411    Fp->seekg((long)nBytes, std::ios_base::cur);
2412 }
2413
2414 /**
2415  * \brief Loads all the needed Dictionaries
2416  * \warning NOT end user intended method !   
2417  */
2418 void Document::Initialise() 
2419 {
2420    RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2421    RefShaDict = NULL;
2422    RLEInfo  = new RLEFramesInfo;
2423    JPEGInfo = new JPEGFragmentsInfo;
2424 }
2425
2426 /**
2427  * \brief   Discover what the swap code is (among little endian, big endian,
2428  *          bad little endian, bad big endian).
2429  *          sw is set
2430  * @return false when we are absolutely sure 
2431  *               it's neither ACR-NEMA nor DICOM
2432  *         true  when we hope ours assuptions are OK
2433  */
2434 bool Document::CheckSwap()
2435 {
2436    // The only guaranted way of finding the swap code is to find a
2437    // group tag since we know it's length has to be of four bytes i.e.
2438    // 0x00000004. Finding the swap code in then straigthforward. Trouble
2439    // occurs when we can't find such group...
2440    
2441    uint32_t  x = 4;  // x : for ntohs
2442    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2443    uint32_t  s32;
2444    uint16_t  s16;
2445        
2446    char deb[256]; //HEADER_LENGTH_TO_READ];
2447     
2448    // First, compare HostByteOrder and NetworkByteOrder in order to
2449    // determine if we shall need to swap bytes (i.e. the Endian type).
2450    if ( x == ntohs(x) )
2451    {
2452       net2host = true;
2453    }
2454    else
2455    {
2456       net2host = false;
2457    }
2458          
2459    // The easiest case is the one of a DICOM header, since it possesses a
2460    // file preamble where it suffice to look for the string "DICM".
2461    Fp->read(deb, HEADER_LENGTH_TO_READ);
2462    
2463    char *entCur = deb + 128;
2464    if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2465    {
2466       dbg.Verbose(1, "Document::CheckSwap:", "looks like DICOM Version3");
2467       
2468       // Next, determine the value representation (VR). Let's skip to the
2469       // first element (0002, 0000) and check there if we find "UL" 
2470       // - or "OB" if the 1st one is (0002,0001) -,
2471       // in which case we (almost) know it is explicit VR.
2472       // WARNING: if it happens to be implicit VR then what we will read
2473       // is the length of the group. If this ascii representation of this
2474       // length happens to be "UL" then we shall believe it is explicit VR.
2475       // FIXME: in order to fix the above warning, we could read the next
2476       // element value (or a couple of elements values) in order to make
2477       // sure we are not commiting a big mistake.
2478       // We need to skip :
2479       // * the 128 bytes of File Preamble (often padded with zeroes),
2480       // * the 4 bytes of "DICM" string,
2481       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2482       // i.e. a total of  136 bytes.
2483       entCur = deb + 136;
2484      
2485       // FIXME : FIXME:
2486       // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2487       // but elem 0002,0010 (Transfert Syntax) tells us the file is
2488       // *Implicit* VR.  -and it is !- 
2489       
2490       if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2491           memcmp(entCur, "OB", (size_t)2) == 0 ||
2492           memcmp(entCur, "UI", (size_t)2) == 0 ||
2493           memcmp(entCur, "CS", (size_t)2) == 0 )  // CS, to remove later
2494                                                     // when Write DCM *adds*
2495       // FIXME
2496       // Use Document::dicom_vr to test all the possibilities
2497       // instead of just checking for UL, OB and UI !? group 0000 
2498       {
2499          Filetype = ExplicitVR;
2500          dbg.Verbose(1, "Document::CheckSwap:",
2501                      "explicit Value Representation");
2502       } 
2503       else 
2504       {
2505          Filetype = ImplicitVR;
2506          dbg.Verbose(1, "Document::CheckSwap:",
2507                      "not an explicit Value Representation");
2508       }
2509       
2510       if ( net2host )
2511       {
2512          SwapCode = 4321;
2513          dbg.Verbose(1, "Document::CheckSwap:",
2514                         "HostByteOrder != NetworkByteOrder");
2515       }
2516       else 
2517       {
2518          SwapCode = 0;
2519          dbg.Verbose(1, "Document::CheckSwap:",
2520                         "HostByteOrder = NetworkByteOrder");
2521       }
2522       
2523       // Position the file position indicator at first tag (i.e.
2524       // after the file preamble and the "DICM" string).
2525       Fp->seekg(0, std::ios_base::beg);
2526       Fp->seekg ( 132L, std::ios_base::beg);
2527       return true;
2528    } // End of DicomV3
2529
2530    // Alas, this is not a DicomV3 file and whatever happens there is no file
2531    // preamble. We can reset the file position indicator to where the data
2532    // is (i.e. the beginning of the file).
2533    dbg.Verbose(1, "Document::CheckSwap:", "not a DICOM Version3 file");
2534    Fp->seekg(0, std::ios_base::beg);
2535
2536    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2537    // By clean we mean that the length of the first tag is written down.
2538    // If this is the case and since the length of the first group HAS to be
2539    // four (bytes), then determining the proper swap code is straightforward.
2540
2541    entCur = deb + 4;
2542    // We assume the array of char we are considering contains the binary
2543    // representation of a 32 bits integer. Hence the following dirty
2544    // trick :
2545    s32 = *((uint32_t *)(entCur));
2546
2547    switch( s32 )
2548    {
2549       case 0x00040000 :
2550          SwapCode = 3412;
2551          Filetype = ACR;
2552          return true;
2553       case 0x04000000 :
2554          SwapCode = 4321;
2555          Filetype = ACR;
2556          return true;
2557       case 0x00000400 :
2558          SwapCode = 2143;
2559          Filetype = ACR;
2560          return true;
2561       case 0x00000004 :
2562          SwapCode = 0;
2563          Filetype = ACR;
2564          return true;
2565       default :
2566          // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2567          // It is time for despaired wild guesses. 
2568          // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2569          //  i.e. the 'group length' element is not present :     
2570          
2571          //  check the supposed-to-be 'group number'
2572          //  in ( 0x0001 .. 0x0008 )
2573          //  to determine ' SwapCode' value .
2574          //  Only 0 or 4321 will be possible 
2575          //  (no oportunity to check for the formerly well known
2576          //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
2577          //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-) 
2578          //  the file IS NOT ACR-NEMA nor DICOM V3
2579          //  Find a trick to tell it the caller...
2580       
2581          s16 = *((uint16_t *)(deb));
2582       
2583          switch ( s16 )
2584          {
2585             case 0x0001 :
2586             case 0x0002 :
2587             case 0x0003 :
2588             case 0x0004 :
2589             case 0x0005 :
2590             case 0x0006 :
2591             case 0x0007 :
2592             case 0x0008 :
2593                SwapCode = 0;
2594                Filetype = ACR;
2595                return true;
2596             case 0x0100 :
2597             case 0x0200 :
2598             case 0x0300 :
2599             case 0x0400 :
2600             case 0x0500 :
2601             case 0x0600 :
2602             case 0x0700 :
2603             case 0x0800 :
2604                SwapCode = 4321;
2605                Filetype = ACR;
2606                return true;
2607             default :
2608                dbg.Verbose(0, "Document::CheckSwap:",
2609                      "ACR/NEMA unfound swap info (Really hopeless !)");
2610                Filetype = Unknown;
2611                return false;
2612          }
2613          // Then the only info we have is the net2host one.
2614          //if (! net2host )
2615          //   SwapCode = 0;
2616          //else
2617          //  SwapCode = 4321;
2618          //return;
2619    }
2620 }
2621
2622
2623
2624 /**
2625  * \brief Restore the unproperly loaded values i.e. the group, the element
2626  *        and the dictionary entry depending on them. 
2627  */
2628 void Document::SwitchSwapToBigEndian() 
2629 {
2630    dbg.Verbose(1, "Document::SwitchSwapToBigEndian",
2631                   "Switching to BigEndian mode.");
2632    if ( SwapCode == 0    ) 
2633    {
2634       SwapCode = 4321;
2635    }
2636    else if ( SwapCode == 4321 ) 
2637    {
2638       SwapCode = 0;
2639    }
2640    else if ( SwapCode == 3412 ) 
2641    {
2642       SwapCode = 2143;
2643    }
2644    else if ( SwapCode == 2143 )
2645    {
2646       SwapCode = 3412;
2647    }
2648 }
2649
2650 /**
2651  * \brief  during parsing, Header Elements too long are not loaded in memory 
2652  * @param newSize
2653  */
2654 void Document::SetMaxSizeLoadEntry(long newSize) 
2655 {
2656    if ( newSize < 0 )
2657    {
2658       return;
2659    }
2660    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2661    {
2662       MaxSizeLoadEntry = 0xffffffff;
2663       return;
2664    }
2665    MaxSizeLoadEntry = newSize;
2666 }
2667
2668
2669 /**
2670  * \brief Header Elements too long will not be printed
2671  * \todo  See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE 
2672  * @param newSize
2673  */
2674 void Document::SetMaxSizePrintEntry(long newSize) 
2675 {
2676    //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2677    if ( newSize < 0 )
2678    {
2679       return;
2680    }
2681    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2682    {
2683       MaxSizePrintEntry = 0xffffffff;
2684       return;
2685    }
2686    MaxSizePrintEntry = newSize;
2687 }
2688
2689
2690
2691 /**
2692  * \brief   Handle broken private tag from Philips NTSCAN
2693  *          where the endianess is being switch to BigEndian for no
2694  *          apparent reason
2695  * @return  no return
2696  */
2697 void Document::HandleBrokenEndian(uint16_t group, uint16_t elem)
2698 {
2699    // Endian reversion. Some files contain groups of tags with reversed endianess.
2700    static int reversedEndian = 0;
2701    // try to fix endian switching in the middle of headers
2702    if ((group == 0xfeff) && (elem == 0x00e0))
2703    {
2704      // start endian swap mark for group found
2705      reversedEndian++;
2706      SwitchSwapToBigEndian();
2707      // fix the tag
2708      group = 0xfffe;
2709      elem = 0xe000;
2710    } 
2711    else if ((group == 0xfffe) && (elem == 0xe00d) && reversedEndian) 
2712    {
2713      // end of reversed endian group
2714      reversedEndian--;
2715      SwitchSwapToBigEndian();
2716    }
2717
2718 }
2719
2720 /**
2721  * \brief   Read the next tag but WITHOUT loading it's value
2722  *          (read the 'Group Number', the 'Element Number',
2723  *           gets the Dict Entry
2724  *          gets the VR, gets the length, gets the offset value)
2725  * @return  On succes the newly created DocEntry, NULL on failure.      
2726  */
2727 DocEntry* Document::ReadNextDocEntry()
2728 {
2729    uint16_t group;
2730    uint16_t elem;
2731
2732    try
2733    {
2734       group = ReadInt16();
2735       elem  = ReadInt16();
2736    }
2737    catch ( FormatError e )
2738    {
2739       // We reached the EOF (or an error occured) therefore 
2740       // header parsing has to be considered as finished.
2741       //std::cout << e;
2742       return 0;
2743    }
2744
2745    HandleBrokenEndian(group, elem);
2746    DocEntry *newEntry = NewDocEntryByNumber(group, elem);
2747    FindDocEntryVR(newEntry);
2748
2749    try
2750    {
2751       FindDocEntryLength(newEntry);
2752    }
2753    catch ( FormatError e )
2754    {
2755       // Call it quits
2756       //std::cout << e;
2757       delete newEntry;
2758       return 0;
2759    }
2760
2761    newEntry->SetOffset(Fp->tellg());  
2762
2763    return newEntry;
2764 }
2765
2766
2767 /**
2768  * \brief   Generate a free TagKey i.e. a TagKey that is not present
2769  *          in the TagHt dictionary.
2770  * @param   group The generated tag must belong to this group.  
2771  * @return  The element of tag with given group which is fee.
2772  */
2773 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group) 
2774 {
2775    for (uint32_t elem = 0; elem < UINT32_MAX; elem++) 
2776    {
2777       TagKey key = DictEntry::TranslateToKey(group, elem);
2778       if (TagHT.count(key) == 0)
2779       {
2780          return elem;
2781       }
2782    }
2783    return UINT32_MAX;
2784 }
2785
2786 /**
2787  * \brief   Assuming the internal file pointer \ref Document::Fp 
2788  *          is placed at the beginning of a tag check whether this
2789  *          tag is (TestGroup, TestElement).
2790  * \warning On success the internal file pointer \ref Document::Fp
2791  *          is modified to point after the tag.
2792  *          On failure (i.e. when the tag wasn't the expected tag
2793  *          (TestGroup, TestElement) the internal file pointer
2794  *          \ref Document::Fp is restored to it's original position.
2795  * @param   testGroup   The expected group of the tag.
2796  * @param   testElement The expected Element of the tag.
2797  * @return  True on success, false otherwise.
2798  */
2799 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2800 {
2801    long positionOnEntry = Fp->tellg();
2802    long currentPosition = Fp->tellg();          // On debugging purposes
2803
2804    //// Read the Item Tag group and element, and make
2805    // sure they are what we expected:
2806    uint16_t itemTagGroup;
2807    uint16_t itemTagElement;
2808    try
2809    {
2810       itemTagGroup   = ReadInt16();
2811       itemTagElement = ReadInt16();
2812    }
2813    catch ( FormatError e )
2814    {
2815       //std::cerr << e << std::endl;
2816       return false;
2817    }
2818    if ( itemTagGroup != testGroup || itemTagElement != testElement )
2819    {
2820       std::ostringstream s;
2821       s << "   We should have found tag (";
2822       s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2823       s << "   but instead we encountered tag (";
2824       s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2825         << std::endl;
2826       s << "  at address: " << (unsigned)currentPosition << std::endl;
2827       dbg.Verbose(0, "Document::ReadItemTagLength: wrong Item Tag found:");
2828       dbg.Verbose(0, s.str().c_str());
2829       Fp->seekg(positionOnEntry, std::ios_base::beg);
2830
2831       return false;
2832    }
2833    return true;
2834 }
2835
2836 /**
2837  * \brief   Assuming the internal file pointer \ref Document::Fp 
2838  *          is placed at the beginning of a tag (TestGroup, TestElement),
2839  *          read the length associated to the Tag.
2840  * \warning On success the internal file pointer \ref Document::Fp
2841  *          is modified to point after the tag and it's length.
2842  *          On failure (i.e. when the tag wasn't the expected tag
2843  *          (TestGroup, TestElement) the internal file pointer
2844  *          \ref Document::Fp is restored to it's original position.
2845  * @param   testGroup   The expected group of the tag.
2846  * @param   testElement The expected Element of the tag.
2847  * @return  On success returns the length associated to the tag. On failure
2848  *          returns 0.
2849  */
2850 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2851 {
2852    long positionOnEntry = Fp->tellg();
2853    (void)positionOnEntry;
2854
2855    if ( !ReadTag(testGroup, testElement) )
2856    {
2857       return 0;
2858    }
2859                                                                                 
2860    //// Then read the associated Item Length
2861    long currentPosition = Fp->tellg();
2862    uint32_t itemLength  = ReadInt32();
2863    {
2864       std::ostringstream s;
2865       s << "Basic Item Length is: "
2866         << itemLength << std::endl;
2867       s << "  at address: " << (unsigned)currentPosition << std::endl;
2868       dbg.Verbose(0, "Document::ReadItemTagLength: ", s.str().c_str());
2869    }
2870    return itemLength;
2871 }
2872
2873 /**
2874  * \brief When parsing the Pixel Data of an encapsulated file, read
2875  *        the basic offset table (when present, and BTW dump it).
2876  */
2877 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2878 {
2879    //// Read the Basic Offset Table Item Tag length...
2880    uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2881
2882    // When present, read the basic offset table itself.
2883    // Notes: - since the presence of this basic offset table is optional
2884    //          we can't rely on it for the implementation, and we will simply
2885    //          trash it's content (when present).
2886    //        - still, when present, we could add some further checks on the
2887    //          lengths, but we won't bother with such fuses for the time being.
2888    if ( itemLength != 0 )
2889    {
2890       char* basicOffsetTableItemValue = new char[itemLength + 1];
2891       Fp->read(basicOffsetTableItemValue, itemLength);
2892
2893 #ifdef GDCM_DEBUG
2894       for (unsigned int i=0; i < itemLength; i += 4 )
2895       {
2896          uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2897                                               uint32_t);
2898          std::ostringstream s;
2899          s << "   Read one length: ";
2900          s << std::hex << individualLength << std::endl;
2901          dbg.Verbose(0,
2902                      "Document::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2903                      s.str().c_str());
2904       }
2905 #endif //GDCM_DEBUG
2906
2907       delete[] basicOffsetTableItemValue;
2908    }
2909 }
2910
2911 /**
2912  * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2913  *        Compute the RLE extra information and store it in \ref RLEInfo
2914  *        for later pixel retrieval usage.
2915  */
2916 void Document::ComputeRLEInfo()
2917 {
2918    TransferSyntaxType ts = GetTransferSyntax();
2919    if ( ts != RLELossless )
2920    {
2921       return;
2922    }
2923
2924    // Encoded pixel data: for the time being we are only concerned with
2925    // Jpeg or RLE Pixel data encodings.
2926    // As stated in PS 3.5-2003, section 8.2 p44:
2927    // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2928    //  value representation OB is used".
2929    // Hence we expect an OB value representation. Concerning OB VR,
2930    // the section PS 3.5-2003, section A.4.c p 58-59, states:
2931    // "For the Value Representations OB and OW, the encoding shall meet the
2932    //   following specifications depending on the Data element tag:"
2933    //   [...snip...]
2934    //    - the first item in the sequence of items before the encoded pixel
2935    //      data stream shall be basic offset table item. The basic offset table
2936    //      item value, however, is not required to be present"
2937
2938    ReadAndSkipEncapsulatedBasicOffsetTable();
2939
2940    // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2941    // Loop on the individual frame[s] and store the information
2942    // on the RLE fragments in a RLEFramesInfo.
2943    // Note: - when only a single frame is present, this is a
2944    //         classical image.
2945    //       - when more than one frame are present, then we are in 
2946    //         the case of a multi-frame image.
2947    long frameLength;
2948    while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2949    { 
2950       // Parse the RLE Header and store the corresponding RLE Segment
2951       // Offset Table information on fragments of this current Frame.
2952       // Note that the fragment pixels themselves are not loaded
2953       // (but just skipped).
2954       long frameOffset = Fp->tellg();
2955
2956       uint32_t nbRleSegments = ReadInt32();
2957       if ( nbRleSegments > 16 )
2958       {
2959          // There should be at most 15 segments (refer to RLEFrame class)
2960          dbg.Verbose(0, "Document::ComputeRLEInfo: too many segments.");
2961       }
2962  
2963       uint32_t rleSegmentOffsetTable[16];
2964       for( int k = 1; k <= 15; k++ )
2965       {
2966          rleSegmentOffsetTable[k] = ReadInt32();
2967       }
2968
2969       // Deduce from both the RLE Header and the frameLength the
2970       // fragment length, and again store this info in a
2971       // RLEFramesInfo.
2972       long rleSegmentLength[15];
2973       // skipping (not reading) RLE Segments
2974       if ( nbRleSegments > 1)
2975       {
2976          for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2977          {
2978              rleSegmentLength[k] =  rleSegmentOffsetTable[k+1]
2979                                   - rleSegmentOffsetTable[k];
2980              SkipBytes(rleSegmentLength[k]);
2981           }
2982        }
2983
2984        rleSegmentLength[nbRleSegments] = frameLength 
2985                                       - rleSegmentOffsetTable[nbRleSegments];
2986        SkipBytes(rleSegmentLength[nbRleSegments]);
2987
2988        // Store the collected info
2989        RLEFrame* newFrameInfo = new RLEFrame;
2990        newFrameInfo->NumberFragments = nbRleSegments;
2991        for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2992        {
2993           newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2994           newFrameInfo->Length[uk] = rleSegmentLength[uk];
2995        }
2996        RLEInfo->Frames.push_back( newFrameInfo );
2997    }
2998
2999    // Make sure that at the end of the item we encounter a 'Sequence
3000    // Delimiter Item':
3001    if ( !ReadTag(0xfffe, 0xe0dd) )
3002    {
3003       dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3004       dbg.Verbose(0, "    item at end of RLE item sequence");
3005    }
3006 }
3007
3008 /**
3009  * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
3010  *        Compute the jpeg extra information (fragment[s] offset[s] and
3011  *        length) and store it[them] in \ref JPEGInfo for later pixel
3012  *        retrieval usage.
3013  */
3014 void Document::ComputeJPEGFragmentInfo()
3015 {
3016    // If you need to, look for comments of ComputeRLEInfo().
3017    if ( ! IsJPEG() )
3018    {
3019       return;
3020    }
3021
3022    ReadAndSkipEncapsulatedBasicOffsetTable();
3023
3024    // Loop on the fragments[s] and store the parsed information in a
3025    // JPEGInfo.
3026    long fragmentLength;
3027    while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
3028    { 
3029       long fragmentOffset = Fp->tellg();
3030
3031        // Store the collected info
3032        JPEGFragment* newFragment = new JPEGFragment;
3033        newFragment->Offset = fragmentOffset;
3034        newFragment->Length = fragmentLength;
3035        JPEGInfo->Fragments.push_back( newFragment );
3036
3037        SkipBytes( fragmentLength );
3038    }
3039
3040    // Make sure that at the end of the item we encounter a 'Sequence
3041    // Delimiter Item':
3042    if ( !ReadTag(0xfffe, 0xe0dd) )
3043    {
3044       dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3045       dbg.Verbose(0, "    item at end of JPEG item sequence");
3046    }
3047 }
3048
3049 /**
3050  * \brief Walk recursively the given \ref DocEntrySet, and feed
3051  *        the given hash table (\ref TagDocEntryHT) with all the
3052  *        \ref DocEntry (Dicom entries) encountered.
3053  *        This method does the job for \ref BuildFlatHashTable.
3054  * @param builtHT Where to collect all the \ref DocEntry encountered
3055  *        when recursively walking the given set.
3056  * @param set The structure to be traversed (recursively).
3057  */
3058 void Document::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
3059                                           DocEntrySet* set )
3060
3061    if (ElementSet* elementSet = dynamic_cast< ElementSet* > ( set ) )
3062    {
3063       TagDocEntryHT const & currentHT = elementSet->GetTagHT();
3064       for( TagDocEntryHT::const_iterator i  = currentHT.begin();
3065                                          i != currentHT.end();
3066                                        ++i)
3067       {
3068          DocEntry* entry = i->second;
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       return;
3083     }
3084
3085    if (SQItem* SQItemSet = dynamic_cast< SQItem* > ( set ) )
3086    {
3087       const ListDocEntry& currentList = SQItemSet->GetDocEntries();
3088       for (ListDocEntry::const_iterator i  = currentList.begin();
3089                                         i != currentList.end();
3090                                       ++i)
3091       {
3092          DocEntry* entry = *i;
3093          if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3094          {
3095             const ListSQItem& items = seqEntry->GetSQItems();
3096             for( ListSQItem::const_iterator item  = items.begin();
3097                                             item != items.end();
3098                                           ++item)
3099             {
3100                BuildFlatHashTableRecurse( builtHT, *item );
3101             }
3102             continue;
3103          }
3104          builtHT[entry->GetKey()] = entry;
3105       }
3106
3107    }
3108 }
3109
3110 /**
3111  * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3112  *        Document.
3113  *
3114  *        The structure used by a Document (through \ref ElementSet),
3115  *        in order to hold the parsed entries of a Dicom header, is a recursive
3116  *        one. This is due to the fact that the sequences (when present)
3117  *        can be nested. Additionaly, the sequence items (represented in
3118  *        gdcm as \ref SQItem) add an extra complexity to the data
3119  *        structure. Hence, a gdcm user whishing to visit all the entries of
3120  *        a Dicom header will need to dig in the gdcm internals (which
3121  *        implies exposing all the internal data structures to the API).
3122  *        In order to avoid this burden to the user, \ref BuildFlatHashTable
3123  *        recursively builds a temporary hash table, which holds all the
3124  *        Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3125  *        std::map<>).
3126  * \warning Of course there is NO integrity constrain between the 
3127  *        returned \ref TagDocEntryHT and the \ref ElementSet used
3128  *        to build it. Hence if the underlying \ref ElementSet is
3129  *        altered, then it is the caller responsability to invoke 
3130  *        \ref BuildFlatHashTable again...
3131  * @return The flat std::map<> we juste build.
3132  */
3133 TagDocEntryHT* Document::BuildFlatHashTable()
3134 {
3135    TagDocEntryHT* FlatHT = new TagDocEntryHT;
3136    BuildFlatHashTableRecurse( *FlatHT, this );
3137    return FlatHT;
3138 }
3139
3140
3141
3142 /**
3143  * \brief   Compares two documents, according to \ref DicomDir rules
3144  * \warning Does NOT work with ACR-NEMA files
3145  * \todo    Find a trick to solve the pb (use RET fields ?)
3146  * @param   document
3147  * @return  true if 'smaller'
3148  */
3149 bool Document::operator<(Document &document)
3150 {
3151    // Patient Name
3152    std::string s1 = GetEntryByNumber(0x0010,0x0010);
3153    std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3154    if(s1 < s2)
3155    {
3156       return true;
3157    }
3158    else if( s1 > s2 )
3159    {
3160       return false;
3161    }
3162    else
3163    {
3164       // Patient ID
3165       s1 = GetEntryByNumber(0x0010,0x0020);
3166       s2 = document.GetEntryByNumber(0x0010,0x0020);
3167       if ( s1 < s2 )
3168       {
3169          return true;
3170       }
3171       else if ( s1 > s2 )
3172       {
3173          return false;
3174       }
3175       else
3176       {
3177          // Study Instance UID
3178          s1 = GetEntryByNumber(0x0020,0x000d);
3179          s2 = document.GetEntryByNumber(0x0020,0x000d);
3180          if ( s1 < s2 )
3181          {
3182             return true;
3183          }
3184          else if( s1 > s2 )
3185          {
3186             return false;
3187          }
3188          else
3189          {
3190             // Serie Instance UID
3191             s1 = GetEntryByNumber(0x0020,0x000e);
3192             s2 = document.GetEntryByNumber(0x0020,0x000e);    
3193             if ( s1 < s2 )
3194             {
3195                return true;
3196             }
3197             else if( s1 > s2 )
3198             {
3199                return false;
3200             }
3201          }
3202       }
3203    }
3204    return false;
3205 }
3206
3207 } // end namespace gdcm
3208
3209 //-----------------------------------------------------------------------------