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