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