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