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