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