]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
Doxygenation
[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 14:32:04 $
7   Version:   $Revision: 1.73 $
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
1543       LoadEntryVoidArea(binEntryPtr);
1544       s << "gdcm::Loaded (BinEntry)";
1545       binEntryPtr->SetValue(s.str());
1546       return;
1547    }
1548     
1549    /// \todo Any compacter code suggested (?)
1550    if ( IsDocEntryAnInteger(entry) )
1551    {   
1552       uint32_t NewInt;
1553       //std::ostringstream s; //shadow previous declaration
1554       int nbInt;
1555       // When short integer(s) are expected, read and convert the following 
1556       // n *two characters properly i.e. consider them as short integers as
1557       // opposed to strings.
1558       // Elements with Value Multiplicity > 1
1559       // contain a set of integers (not a single one)       
1560       if (vr == "US" || vr == "SS")
1561       {
1562          nbInt = length / 2;
1563          NewInt = ReadInt16();
1564          s << NewInt;
1565          if (nbInt > 1)
1566          {
1567             for (int i=1; i < nbInt; i++)
1568             {
1569                s << '\\';
1570                NewInt = ReadInt16();
1571                s << NewInt;
1572             }
1573          }
1574       }
1575       // See above comment on multiple integers (mutatis mutandis).
1576       else if (vr == "UL" || vr == "SL")
1577       {
1578          nbInt = length / 4;
1579          NewInt = ReadInt32();
1580          s << NewInt;
1581          if (nbInt > 1)
1582          {
1583             for (int i=1; i < nbInt; i++)
1584             {
1585                s << '\\';
1586                NewInt = ReadInt32();
1587                s << NewInt;
1588             }
1589          }
1590       }
1591 #ifdef GDCM_NO_ANSI_STRING_STREAM
1592       s << std::ends; // to avoid oddities on Solaris
1593 #endif //GDCM_NO_ANSI_STRING_STREAM
1594
1595       ((gdcmValEntry *)entry)->SetValue(s.str());
1596       return;
1597    }
1598    
1599    // We need an additional byte for storing \0 that is not on disk
1600    //std::string newValue(length,0);
1601    //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);  
1602    //rah !! I can't believe it could work, normally this is a const char* !!!
1603    char *str = new char[length+1];
1604    item_read = fread(str, (size_t)length, (size_t)1, Fp);
1605    str[length] = '\0';
1606    std::string newValue = str;
1607    delete[] str;
1608    if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry* >(entry) )
1609    {  
1610       if ( item_read != 1 )
1611       {
1612          dbg.Verbose(1, "gdcmDocument::LoadDocEntry",
1613                         "unread element value");
1614          valEntry->SetValue(GDCM_UNREAD);
1615          return;
1616       }
1617
1618       if( vr == "UI" )
1619       {
1620          // Because of correspondance with the VR dic
1621          valEntry->SetValue(newValue);
1622       }
1623       else
1624       {
1625          valEntry->SetValue(newValue);
1626       }
1627    }
1628    else
1629    {
1630       dbg.Error(true, "gdcmDocument::LoadDocEntry"
1631                       "Should have a ValEntry, here !");
1632    }
1633 }
1634
1635
1636 /**
1637  * \brief  Find the value Length of the passed Header Entry
1638  * @param  entry Header Entry whose length of the value shall be loaded. 
1639  */
1640 void gdcmDocument::FindDocEntryLength( gdcmDocEntry *entry )
1641    throw ( gdcmFormatError )
1642 {
1643    uint16_t element = entry->GetElement();
1644    std::string  vr  = entry->GetVR();
1645    uint16_t length16;       
1646    
1647    if ( Filetype == gdcmExplicitVR && !entry->IsImplicitVR() ) 
1648    {
1649       if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" ) 
1650       {
1651          // The following reserved two bytes (see PS 3.5-2001, section
1652          // 7.1.2 Data element structure with explicit vr p27) must be
1653          // skipped before proceeding on reading the length on 4 bytes.
1654          fseek(Fp, 2L, SEEK_CUR);
1655          uint32_t length32 = ReadInt32();
1656
1657          if ( vr == "OB" && length32 == 0xffffffff ) 
1658          {
1659             uint32_t lengthOB;
1660             try 
1661             {
1662                lengthOB = FindDocEntryLengthOB();
1663             }
1664             catch ( gdcmFormatUnexpected )
1665             {
1666                // Computing the length failed (this happens with broken
1667                // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1668                // chance to get the pixels by deciding the element goes
1669                // until the end of the file. Hence we artificially fix the
1670                // the length and proceed.
1671                long currentPosition = ftell(Fp);
1672                fseek(Fp,0L,SEEK_END);
1673                long lengthUntilEOF = ftell(Fp) - currentPosition;
1674                fseek(Fp, currentPosition, SEEK_SET);
1675                entry->SetLength(lengthUntilEOF);
1676                return;
1677             }
1678             entry->SetLength(lengthOB);
1679             return;
1680          }
1681          FixDocEntryFoundLength(entry, length32); 
1682          return;
1683       }
1684
1685       // Length is encoded on 2 bytes.
1686       length16 = ReadInt16();
1687       
1688       // We can tell the current file is encoded in big endian (like
1689       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1690       // and it's value is the one of the encoding of a big endian file.
1691       // In order to deal with such big endian encoded files, we have
1692       // (at least) two strategies:
1693       // * when we load the "Transfer Syntax" tag with value of big endian
1694       //   encoding, we raise the proper flags. Then we wait for the end
1695       //   of the META group (0x0002) among which is "Transfer Syntax",
1696       //   before switching the swap code to big endian. We have to postpone
1697       //   the switching of the swap code since the META group is fully encoded
1698       //   in little endian, and big endian coding only starts at the next
1699       //   group. The corresponding code can be hard to analyse and adds
1700       //   many additional unnecessary tests for regular tags.
1701       // * the second strategy consists in waiting for trouble, that shall
1702       //   appear when we find the first group with big endian encoding. This
1703       //   is easy to detect since the length of a "Group Length" tag (the
1704       //   ones with zero as element number) has to be of 4 (0x0004). When we
1705       //   encounter 1024 (0x0400) chances are the encoding changed and we
1706       //   found a group with big endian encoding.
1707       // We shall use this second strategy. In order to make sure that we
1708       // can interpret the presence of an apparently big endian encoded
1709       // length of a "Group Length" without committing a big mistake, we
1710       // add an additional check: we look in the already parsed elements
1711       // for the presence of a "Transfer Syntax" whose value has to be "big
1712       // endian encoding". When this is the case, chances are we have got our
1713       // hands on a big endian encoded file: we switch the swap code to
1714       // big endian and proceed...
1715       if ( element  == 0x0000 && length16 == 0x0400 ) 
1716       {
1717          if ( !IsExplicitVRBigEndianTransferSyntax() ) 
1718          {
1719             throw gdcmFormatError( "gdcmDocument::FindDocEntryLength()",
1720                                    " not explicit VR." );
1721             return;
1722          }
1723          length16 = 4;
1724          SwitchSwapToBigEndian();
1725          // Restore the unproperly loaded values i.e. the group, the element
1726          // and the dictionary entry depending on them.
1727          uint16_t correctGroup = SwapShort( entry->GetGroup() );
1728          uint16_t correctElem  = SwapShort( entry->GetElement() );
1729          gdcmDictEntry* newTag = GetDictEntryByNumber( correctGroup,
1730                                                        correctElem );
1731          if ( !newTag )
1732          {
1733             // This correct tag is not in the dictionary. Create a new one.
1734             newTag = NewVirtualDictEntry(correctGroup, correctElem);
1735          }
1736          // FIXME this can create a memory leaks on the old entry that be
1737          // left unreferenced.
1738          entry->SetDictEntry( newTag );
1739       }
1740        
1741       // Heuristic: well, some files are really ill-formed.
1742       if ( length16 == 0xffff) 
1743       {
1744          // 0xffff means that we deal with 'Unknown Length' Sequence  
1745          length16 = 0;
1746       }
1747       FixDocEntryFoundLength( entry, (uint32_t)length16 );
1748       return;
1749    }
1750    else
1751    {
1752       // Either implicit VR or a non DICOM conformal (see note below) explicit
1753       // VR that ommited the VR of (at least) this element. Farts happen.
1754       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1755       // on Data elements "Implicit and Explicit VR Data Elements shall
1756       // not coexist in a Data Set and Data Sets nested within it".]
1757       // Length is on 4 bytes.
1758       
1759       FixDocEntryFoundLength( entry, ReadInt32() );
1760       return;
1761    }
1762 }
1763
1764 /**
1765  * \brief     Find the Value Representation of the current Dicom Element.
1766  * @param     entry
1767  */
1768 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *entry )
1769 {
1770    if ( Filetype != gdcmExplicitVR )
1771    {
1772       return;
1773    }
1774
1775    char vr[3];
1776
1777    long positionOnEntry = ftell(Fp);
1778    // Warning: we believe this is explicit VR (Value Representation) because
1779    // we used a heuristic that found "UL" in the first tag. Alas this
1780    // doesn't guarantee that all the tags will be in explicit VR. In some
1781    // cases (see e-film filtered files) one finds implicit VR tags mixed
1782    // within an explicit VR file. Hence we make sure the present tag
1783    // is in explicit VR and try to fix things if it happens not to be
1784    // the case.
1785    
1786    fread (vr, (size_t)2,(size_t)1, Fp);
1787    vr[2] = 0;
1788
1789    if( !CheckDocEntryVR(entry, vr) )
1790    {
1791       fseek(Fp, positionOnEntry, SEEK_SET);
1792       // When this element is known in the dictionary we shall use, e.g. for
1793       // the semantics (see the usage of IsAnInteger), the VR proposed by the
1794       // dictionary entry. Still we have to flag the element as implicit since
1795       // we know now our assumption on expliciteness is not furfilled.
1796       // avoid  .
1797       if ( entry->IsVRUnknown() )
1798       {
1799          entry->SetVR("Implicit");
1800       }
1801       entry->SetImplicitVR();
1802    }
1803 }
1804
1805 /**
1806  * \brief     Check the correspondance between the VR of the header entry
1807  *            and the taken VR. If they are different, the header entry is 
1808  *            updated with the new VR.
1809  * @param     entry Header Entry to check
1810  * @param     vr    Dicom Value Representation
1811  * @return    false if the VR is incorrect of if the VR isn't referenced
1812  *            otherwise, it returns true
1813 */
1814 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *entry, gdcmVRKey vr)
1815 {
1816    char msg[100]; // for sprintf
1817    bool realExplicit = true;
1818
1819    // Assume we are reading a falsely explicit VR file i.e. we reached
1820    // a tag where we expect reading a VR but are in fact we read the
1821    // first to bytes of the length. Then we will interogate (through find)
1822    // the dicom_vr dictionary with oddities like "\004\0" which crashes
1823    // both GCC and VC++ implementations of the STL map. Hence when the
1824    // expected VR read happens to be non-ascii characters we consider
1825    // we hit falsely explicit VR tag.
1826
1827    if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1828    {
1829       realExplicit = false;
1830    }
1831
1832    // CLEANME searching the dicom_vr at each occurence is expensive.
1833    // PostPone this test in an optional integrity check at the end
1834    // of parsing or only in debug mode.
1835    if ( realExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1836    {
1837       realExplicit = false;
1838    }
1839
1840    if ( !realExplicit ) 
1841    {
1842       // We thought this was explicit VR, but we end up with an
1843       // implicit VR tag. Let's backtrack.   
1844       sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n", 
1845                    entry->GetGroup(), entry->GetElement());
1846       dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1847
1848       if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1849       {
1850          // Group length is UL !
1851          gdcmDictEntry* newEntry = NewVirtualDictEntry(
1852                                    entry->GetGroup(), entry->GetElement(),
1853                                    "UL", "FIXME", "Group Length");
1854          entry->SetDictEntry( newEntry );
1855       }
1856       return false;
1857    }
1858
1859    if ( entry->IsVRUnknown() )
1860    {
1861       // When not a dictionary entry, we can safely overwrite the VR.
1862       if( entry->GetElement() == 0x0000 )
1863       {
1864          // Group length is UL !
1865          entry->SetVR("UL");
1866       }
1867       else
1868       {
1869          entry->SetVR(vr);
1870       }
1871    }
1872    else if ( entry->GetVR() != vr ) 
1873    {
1874       // The VR present in the file and the dictionary disagree. We assume
1875       // the file writer knew best and use the VR of the file. Since it would
1876       // be unwise to overwrite the VR of a dictionary (since it would
1877       // compromise it's next user), we need to clone the actual DictEntry
1878       // and change the VR for the read one.
1879       gdcmDictEntry* newEntry = NewVirtualDictEntry(
1880                                 entry->GetGroup(), entry->GetElement(),
1881                                 vr, "FIXME", entry->GetName());
1882       entry->SetDictEntry(newEntry);
1883    }
1884
1885    return true; 
1886 }
1887
1888 /**
1889  * \brief   Get the transformed value of the header entry. The VR value 
1890  *          is used to define the transformation to operate on the value
1891  * \warning NOT end user intended method !
1892  * @param   entry entry to tranform
1893  * @return  Transformed entry value
1894  */
1895 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *entry)
1896 {
1897    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1898    {
1899       std::string val = ((gdcmValEntry *)entry)->GetValue();
1900       std::string vr  = entry->GetVR();
1901       uint32_t length = entry->GetLength();
1902       std::ostringstream s;
1903       int nbInt;
1904
1905       // When short integer(s) are expected, read and convert the following 
1906       // n * 2 bytes properly i.e. as a multivaluated strings
1907       // (each single value is separated fromthe next one by '\'
1908       // as usual for standard multivaluated filels
1909       // Elements with Value Multiplicity > 1
1910       // contain a set of short integers (not a single one) 
1911    
1912       if( vr == "US" || vr == "SS" )
1913       {
1914          uint16_t newInt16;
1915
1916          nbInt = length / 2;
1917          for (int i=0; i < nbInt; i++) 
1918          {
1919             if( i != 0 )
1920             {
1921                s << '\\';
1922             }
1923             newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1924             newInt16 = SwapShort( newInt16 );
1925             s << newInt16;
1926          }
1927       }
1928
1929       // When integer(s) are expected, read and convert the following 
1930       // n * 4 bytes properly i.e. as a multivaluated strings
1931       // (each single value is separated fromthe next one by '\'
1932       // as usual for standard multivaluated filels
1933       // Elements with Value Multiplicity > 1
1934       // contain a set of integers (not a single one) 
1935       else if( vr == "UL" || vr == "SL" )
1936       {
1937          uint32_t newInt32;
1938
1939          nbInt = length / 4;
1940          for (int i=0; i < nbInt; i++) 
1941          {
1942             if( i != 0)
1943             {
1944                s << '\\';
1945             }
1946             newInt32 = ( val[4*i+0] & 0xFF )
1947                     + (( val[4*i+1] & 0xFF ) <<  8 )
1948                     + (( val[4*i+2] & 0xFF ) << 16 )
1949                     + (( val[4*i+3] & 0xFF ) << 24 );
1950             newInt32 = SwapLong( newInt32 );
1951             s << newInt32;
1952          }
1953       }
1954 #ifdef GDCM_NO_ANSI_STRING_STREAM
1955       s << std::ends; // to avoid oddities on Solaris
1956 #endif //GDCM_NO_ANSI_STRING_STREAM
1957       return s.str();
1958    }
1959
1960    return ((gdcmValEntry *)entry)->GetValue();
1961 }
1962
1963 /**
1964  * \brief   Get the reverse transformed value of the header entry. The VR 
1965  *          value is used to define the reverse transformation to operate on
1966  *          the value
1967  * \warning NOT end user intended method !
1968  * @param   entry Entry to reverse transform
1969  * @return  Reverse transformed entry value
1970  */
1971 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry* entry)
1972 {
1973    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1974    {
1975       std::string vr = entry->GetVR();
1976       std::vector<std::string> tokens;
1977       std::ostringstream s;
1978
1979       if ( vr == "US" || vr == "SS" ) 
1980       {
1981          uint16_t newInt16;
1982
1983          tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1984          Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
1985          for (unsigned int i=0; i<tokens.size(); i++) 
1986          {
1987             newInt16 = atoi(tokens[i].c_str());
1988             s << (  newInt16        & 0xFF ) 
1989               << (( newInt16 >> 8 ) & 0xFF );
1990          }
1991          tokens.clear();
1992       }
1993       if ( vr == "UL" || vr == "SL")
1994       {
1995          uint32_t newInt32;
1996
1997          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1998          Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
1999          for (unsigned int i=0; i<tokens.size();i++) 
2000          {
2001             newInt32 = atoi(tokens[i].c_str());
2002             s << (char)(  newInt32         & 0xFF ) 
2003               << (char)(( newInt32 >>  8 ) & 0xFF )
2004               << (char)(( newInt32 >> 16 ) & 0xFF )
2005               << (char)(( newInt32 >> 24 ) & 0xFF );
2006          }
2007          tokens.clear();
2008       }
2009
2010 #ifdef GDCM_NO_ANSI_STRING_STREAM
2011       s << std::ends; // to avoid oddities on Solaris
2012 #endif //GDCM_NO_ANSI_STRING_STREAM
2013       return s.str();
2014    }
2015
2016    return ((gdcmValEntry *)entry)->GetValue();
2017 }
2018
2019 /**
2020  * \brief   Skip a given Header Entry 
2021  * \warning NOT end user intended method !
2022  * @param   entry entry to skip
2023  */
2024 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry) 
2025 {
2026    SkipBytes(entry->GetLength());
2027 }
2028
2029 /**
2030  * \brief   Skips to the begining of the next Header Entry 
2031  * \warning NOT end user intended method !
2032  * @param   entry entry to skip
2033  */
2034 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry) 
2035 {
2036    fseek(Fp, (long)(entry->GetOffset()),     SEEK_SET);
2037    fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2038 }
2039
2040 /**
2041  * \brief   When the length of an element value is obviously wrong (because
2042  *          the parser went Jabberwocky) one can hope improving things by
2043  *          applying some heuristics.
2044  * @param   entry entry to check
2045  * @param   foundLength fist assumption about length    
2046  */
2047 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *entry,
2048                                           uint32_t foundLength)
2049 {
2050    entry->SetReadLength( foundLength ); // will be updated only if a bug is found        
2051    if ( foundLength == 0xffffffff)
2052    {
2053       foundLength = 0;
2054    }
2055    
2056    uint16_t gr = entry->GetGroup();
2057    uint16_t el = entry->GetElement(); 
2058      
2059    if ( foundLength % 2)
2060    {
2061       std::ostringstream s;
2062       s << "Warning : Tag with uneven length "
2063         << foundLength 
2064         <<  " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2065       dbg.Verbose(0, s.str().c_str());
2066    }
2067       
2068    //////// Fix for some naughty General Electric images.
2069    // Allthough not recent many such GE corrupted images are still present
2070    // on Creatis hard disks. Hence this fix shall remain when such images
2071    // are no longer in user (we are talking a few years, here)...
2072    // Note: XMedCom probably uses such a trick since it is able to read
2073    //       those pesky GE images ...
2074    if ( foundLength == 13)
2075    {
2076       // Only happens for this length !
2077       if ( entry->GetGroup()   != 0x0008
2078       || ( entry->GetElement() != 0x0070
2079         && entry->GetElement() != 0x0080 ) )
2080       {
2081          foundLength = 10;
2082          entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2083       }
2084    }
2085
2086    //////// Fix for some brain-dead 'Leonardo' Siemens images.
2087    // Occurence of such images is quite low (unless one leaves close to a
2088    // 'Leonardo' source. Hence, one might consider commenting out the
2089    // following fix on efficiency reasons.
2090    else if ( entry->GetGroup()   == 0x0009 
2091         && ( entry->GetElement() == 0x1113
2092           || entry->GetElement() == 0x1114 ) )
2093    {
2094       foundLength = 4;
2095       entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2096    } 
2097  
2098    else if ( entry->GetVR() == "SQ" )
2099    {
2100       foundLength = 0;      // ReadLength is unchanged 
2101    } 
2102     
2103    //////// We encountered a 'delimiter' element i.e. a tag of the form 
2104    // "fffe|xxxx" which is just a marker. Delimiters length should not be
2105    // taken into account.
2106    else if( entry->GetGroup() == 0xfffe )
2107    {    
2108      // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2109      // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2110      // causes extra troubles...
2111      if( entry->GetElement() != 0x0000 )
2112      {
2113         foundLength = 0;
2114      }
2115    } 
2116            
2117    entry->SetUsableLength(foundLength);
2118 }
2119
2120 /**
2121  * \brief   Apply some heuristics to predict whether the considered 
2122  *          element value contains/represents an integer or not.
2123  * @param   entry The element value on which to apply the predicate.
2124  * @return  The result of the heuristical predicate.
2125  */
2126 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *entry)
2127 {
2128    uint16_t element = entry->GetElement();
2129    uint16_t group   = entry->GetGroup();
2130    std::string  vr  = entry->GetVR();
2131    uint32_t length  = entry->GetLength();
2132
2133    // When we have some semantics on the element we just read, and if we
2134    // a priori know we are dealing with an integer, then we shall be
2135    // able to swap it's element value properly.
2136    if ( element == 0 )  // This is the group length of the group
2137    {  
2138       if ( length == 4 )
2139       {
2140          return true;
2141       }
2142       else 
2143       {
2144          // Allthough this should never happen, still some images have a
2145          // corrupted group length [e.g. have a glance at offset x(8336) of
2146          // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2147          // Since for dicom compliant and well behaved headers, the present
2148          // test is useless (and might even look a bit paranoid), when we
2149          // encounter such an ill-formed image, we simply display a warning
2150          // message and proceed on parsing (while crossing fingers).
2151          std::ostringstream s;
2152          int filePosition = ftell(Fp);
2153          s << "Erroneous Group Length element length  on : (" \
2154            << std::hex << group << " , " << element 
2155            << ") -before- position x(" << filePosition << ")"
2156            << "lgt : " << length;
2157          dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2158       }
2159    }
2160
2161    if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2162    {
2163       return true;
2164    }
2165    
2166    return false;
2167 }
2168
2169 /**
2170  * \brief  Find the Length till the next sequence delimiter
2171  * \warning NOT end user intended method !
2172  * @return 
2173  */
2174
2175 uint32_t gdcmDocument::FindDocEntryLengthOB()
2176    throw( gdcmFormatUnexpected )
2177 {
2178    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2179    long positionOnEntry = ftell(Fp);
2180    bool foundSequenceDelimiter = false;
2181    uint32_t totalLength = 0;
2182
2183    while ( !foundSequenceDelimiter )
2184    {
2185       uint16_t group;
2186       uint16_t elem;
2187       try
2188       {
2189          group = ReadInt16();
2190          elem  = ReadInt16();   
2191       }
2192       catch ( gdcmFormatError )
2193       {
2194          throw gdcmFormatError("gdcmDocument::FindDocEntryLengthOB()",
2195                                " group or element not present.");
2196       }
2197
2198       // We have to decount the group and element we just read
2199       totalLength += 4;
2200      
2201       if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2202       {
2203          dbg.Verbose(1, "gdcmDocument::FindDocEntryLengthOB: neither an Item "
2204                         "tag nor a Sequence delimiter tag."); 
2205          fseek(Fp, positionOnEntry, SEEK_SET);
2206          throw gdcmFormatUnexpected("gdcmDocument::FindDocEntryLengthOB()",
2207                                     "Neither an Item tag nor a Sequence "
2208                                     "delimiter tag.");
2209       }
2210
2211       if ( elem == 0xe0dd )
2212       {
2213          foundSequenceDelimiter = true;
2214       }
2215
2216       uint32_t itemLength = ReadInt32();
2217       // We add 4 bytes since we just read the ItemLength with ReadInt32
2218       totalLength += itemLength + 4;
2219       SkipBytes(itemLength);
2220       
2221       if ( foundSequenceDelimiter )
2222       {
2223          break;
2224       }
2225    }
2226    fseek(Fp, positionOnEntry, SEEK_SET);
2227    return totalLength;
2228 }
2229
2230 /**
2231  * \brief Reads a supposed to be 16 Bits integer
2232  *       (swaps it depending on processor endianity) 
2233  * @return read value
2234  */
2235 uint16_t gdcmDocument::ReadInt16()
2236    throw( gdcmFormatError )
2237 {
2238    uint16_t g;
2239    size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2240    if ( item_read != 1 )
2241    {
2242       if( ferror(Fp) )
2243       {
2244          throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2245       }
2246       throw gdcmFormatError( "gdcmDocument::ReadInt16()", "EOF." );
2247    }
2248    g = SwapShort(g); 
2249    return g;
2250 }
2251
2252 /**
2253  * \brief  Reads a supposed to be 32 Bits integer
2254  *         (swaps it depending on processor endianity)  
2255  * @return read value
2256  */
2257 uint32_t gdcmDocument::ReadInt32()
2258    throw( gdcmFormatError )
2259 {
2260    uint32_t g;
2261    size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2262    if ( item_read != 1 )
2263    {
2264       if( ferror(Fp) )
2265       {
2266          throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2267       }
2268       throw gdcmFormatError( "gdcmDocument::ReadInt32()", "EOF." );
2269    }
2270    g = SwapLong(g);
2271    return g;
2272 }
2273
2274 /**
2275  * \brief skips bytes inside the source file 
2276  * \warning NOT end user intended method !
2277  * @return 
2278  */
2279 void gdcmDocument::SkipBytes(uint32_t nBytes)
2280 {
2281    //FIXME don't dump the returned value
2282    (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2283 }
2284
2285 /**
2286  * \brief Loads all the needed Dictionaries
2287  * \warning NOT end user intended method !   
2288  */
2289 void gdcmDocument::Initialise() 
2290 {
2291    RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2292    RefShaDict = NULL;
2293 }
2294
2295 /**
2296  * \brief   Discover what the swap code is (among little endian, big endian,
2297  *          bad little endian, bad big endian).
2298  *          sw is set
2299  * @return false when we are absolutely sure 
2300  *               it's neither ACR-NEMA nor DICOM
2301  *         true  when we hope ours assuptions are OK
2302  */
2303 bool gdcmDocument::CheckSwap()
2304 {
2305    // The only guaranted way of finding the swap code is to find a
2306    // group tag since we know it's length has to be of four bytes i.e.
2307    // 0x00000004. Finding the swap code in then straigthforward. Trouble
2308    // occurs when we can't find such group...
2309    
2310    uint32_t  x = 4;  // x : for ntohs
2311    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2312    uint32_t  s32;
2313    uint16_t  s16;
2314        
2315    char deb[HEADER_LENGTH_TO_READ];
2316     
2317    // First, compare HostByteOrder and NetworkByteOrder in order to
2318    // determine if we shall need to swap bytes (i.e. the Endian type).
2319    if ( x == ntohs(x) )
2320    {
2321       net2host = true;
2322    }
2323    else
2324    {
2325       net2host = false;
2326    }
2327          
2328    // The easiest case is the one of a DICOM header, since it possesses a
2329    // file preamble where it suffice to look for the string "DICM".
2330    int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2331    (void)lgrLue;  //FIXME not used
2332    
2333    char *entCur = deb + 128;
2334    if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2335    {
2336       dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2337       
2338       // Next, determine the value representation (VR). Let's skip to the
2339       // first element (0002, 0000) and check there if we find "UL" 
2340       // - or "OB" if the 1st one is (0002,0001) -,
2341       // in which case we (almost) know it is explicit VR.
2342       // WARNING: if it happens to be implicit VR then what we will read
2343       // is the length of the group. If this ascii representation of this
2344       // length happens to be "UL" then we shall believe it is explicit VR.
2345       // FIXME: in order to fix the above warning, we could read the next
2346       // element value (or a couple of elements values) in order to make
2347       // sure we are not commiting a big mistake.
2348       // We need to skip :
2349       // * the 128 bytes of File Preamble (often padded with zeroes),
2350       // * the 4 bytes of "DICM" string,
2351       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2352       // i.e. a total of  136 bytes.
2353       entCur = deb + 136;
2354      
2355       // FIXME : FIXME:
2356       // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2357       // but elem 0002,0010 (Transfert Syntax) tells us the file is
2358       // *Implicit* VR.  -and it is !- 
2359       
2360       if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2361           memcmp(entCur, "OB", (size_t)2) == 0 ||
2362           memcmp(entCur, "UI", (size_t)2) == 0 ||
2363           memcmp(entCur, "CS", (size_t)2) == 0 )  // CS, to remove later
2364                                                     // when Write DCM *adds*
2365       // FIXME
2366       // Use gdcmDocument::dicom_vr to test all the possibilities
2367       // instead of just checking for UL, OB and UI !? group 0000 
2368       {
2369          Filetype = gdcmExplicitVR;
2370          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2371                      "explicit Value Representation");
2372       } 
2373       else 
2374       {
2375          Filetype = gdcmImplicitVR;
2376          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2377                      "not an explicit Value Representation");
2378       }
2379       
2380       if ( net2host )
2381       {
2382          SwapCode = 4321;
2383          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2384                         "HostByteOrder != NetworkByteOrder");
2385       }
2386       else 
2387       {
2388          SwapCode = 0;
2389          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2390                         "HostByteOrder = NetworkByteOrder");
2391       }
2392       
2393       // Position the file position indicator at first tag (i.e.
2394       // after the file preamble and the "DICM" string).
2395       rewind(Fp);
2396       fseek (Fp, 132L, SEEK_SET);
2397       return true;
2398    } // End of DicomV3
2399
2400    // Alas, this is not a DicomV3 file and whatever happens there is no file
2401    // preamble. We can reset the file position indicator to where the data
2402    // is (i.e. the beginning of the file).
2403    dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2404    rewind(Fp);
2405
2406    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2407    // By clean we mean that the length of the first tag is written down.
2408    // If this is the case and since the length of the first group HAS to be
2409    // four (bytes), then determining the proper swap code is straightforward.
2410
2411    entCur = deb + 4;
2412    // We assume the array of char we are considering contains the binary
2413    // representation of a 32 bits integer. Hence the following dirty
2414    // trick :
2415    s32 = *((uint32_t *)(entCur));
2416       
2417    switch( s32 )
2418    {
2419       case 0x00040000 :
2420          SwapCode = 3412;
2421          Filetype = gdcmACR;
2422          return true;
2423       case 0x04000000 :
2424          SwapCode = 4321;
2425          Filetype = gdcmACR;
2426          return true;
2427       case 0x00000400 :
2428          SwapCode = 2143;
2429          Filetype = gdcmACR;
2430          return true;
2431       case 0x00000004 :
2432          SwapCode = 0;
2433          Filetype = gdcmACR;
2434          return true;
2435       default :
2436          // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2437          // It is time for despaired wild guesses. 
2438          // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2439          //  i.e. the 'group length' element is not present :     
2440          
2441          //  check the supposed to be 'group number'
2442          //  0x0002 or 0x0004 or 0x0008
2443          //  to determine ' SwapCode' value .
2444          //  Only 0 or 4321 will be possible 
2445          //  (no oportunity to check for the formerly well known
2446          //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
2447          //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-) 
2448          //  the file IS NOT ACR-NEMA nor DICOM V3
2449          //  Find a trick to tell it the caller...
2450       
2451          s16 = *((uint16_t *)(deb));
2452       
2453          switch ( s16 )
2454          {
2455             case 0x0002 :
2456             case 0x0004 :
2457             case 0x0008 :      
2458                SwapCode = 0;
2459                Filetype = gdcmACR;
2460                return true;
2461             case 0x0200 :
2462             case 0x0400 :
2463             case 0x0800 : 
2464                SwapCode = 4321;
2465                Filetype = gdcmACR;
2466                return true;
2467             default :
2468                dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2469                      "ACR/NEMA unfound swap info (Really hopeless !)"); 
2470                Filetype = gdcmUnknown;     
2471                return false;
2472          }
2473          // Then the only info we have is the net2host one.
2474          //if (! net2host )
2475          //   SwapCode = 0;
2476          //else
2477          //  SwapCode = 4321;
2478          //return;
2479    }
2480 }
2481
2482 /**
2483  * \brief Restore the unproperly loaded values i.e. the group, the element
2484  *        and the dictionary entry depending on them. 
2485  */
2486 void gdcmDocument::SwitchSwapToBigEndian() 
2487 {
2488    dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2489                   "Switching to BigEndian mode.");
2490    if ( SwapCode == 0    ) 
2491    {
2492       SwapCode = 4321;
2493    }
2494    else if ( SwapCode == 4321 ) 
2495    {
2496       SwapCode = 0;
2497    }
2498    else if ( SwapCode == 3412 ) 
2499    {
2500       SwapCode = 2143;
2501    }
2502    else if ( SwapCode == 2143 )
2503    {
2504       SwapCode = 3412;
2505    }
2506 }
2507
2508 /**
2509  * \brief  during parsing, Header Elements too long are not loaded in memory 
2510  * @param newSize
2511  */
2512 void gdcmDocument::SetMaxSizeLoadEntry(long newSize) 
2513 {
2514    if ( newSize < 0 )
2515    {
2516       return;
2517    }
2518    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2519    {
2520       MaxSizeLoadEntry = 0xffffffff;
2521       return;
2522    }
2523    MaxSizeLoadEntry = newSize;
2524 }
2525
2526
2527 /**
2528  * \brief Header Elements too long will not be printed
2529  * \todo  See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE 
2530  * @param newSize
2531  */
2532 void gdcmDocument::SetMaxSizePrintEntry(long newSize) 
2533 {
2534    //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2535    if ( newSize < 0 )
2536    {
2537       return;
2538    }
2539    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2540    {
2541       MaxSizePrintEntry = 0xffffffff;
2542       return;
2543    }
2544    MaxSizePrintEntry = newSize;
2545 }
2546
2547
2548
2549 /**
2550  * \brief   Read the next tag but WITHOUT loading it's value
2551  *          (read the 'Group Number', the 'Element Number',
2552  *           gets the Dict Entry
2553  *          gets the VR, gets the length, gets the offset value)
2554  * @return  On succes the newly created DocEntry, NULL on failure.      
2555  */
2556 gdcmDocEntry* gdcmDocument::ReadNextDocEntry()
2557 {
2558    uint16_t group;
2559    uint16_t elem;
2560
2561    try
2562    {
2563       group = ReadInt16();
2564       elem  = ReadInt16();
2565    }
2566    catch ( gdcmFormatError e )
2567    {
2568       // We reached the EOF (or an error occured) therefore 
2569       // header parsing has to be considered as finished.
2570       //std::cout << e;
2571       return 0;
2572    }
2573
2574    gdcmDocEntry *newEntry = NewDocEntryByNumber(group, elem);
2575    FindDocEntryVR(newEntry);
2576
2577    try
2578    {
2579       FindDocEntryLength(newEntry);
2580    }
2581    catch ( gdcmFormatError e )
2582    {
2583       // Call it quits
2584       //std::cout << e;
2585       delete newEntry;
2586       return 0;
2587    }
2588
2589    newEntry->SetOffset(ftell(Fp));  
2590
2591    return newEntry;
2592 }
2593
2594
2595 /**
2596  * \brief   Generate a free gdcmTagKey i.e. a gdcmTagKey that is not present
2597  *          in the TagHt dictionary.
2598  * @param   group The generated tag must belong to this group.  
2599  * @return  The element of tag with given group which is fee.
2600  */
2601 uint32_t gdcmDocument::GenerateFreeTagKeyInGroup(uint16_t group) 
2602 {
2603    for (uint32_t elem = 0; elem < UINT32_MAX; elem++) 
2604    {
2605       gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2606       if (TagHT.count(key) == 0)
2607       {
2608          return elem;
2609       }
2610    }
2611    return UINT32_MAX;
2612 }
2613
2614 /**
2615  * \brief   Assuming the internal file pointer \ref gdcmDocument::Fp 
2616  *          is placed at the beginning of a tag check whether this
2617  *          tag is (TestGroup, TestElement).
2618  * \warning On success the internal file pointer \ref gdcmDocument::Fp
2619  *          is modified to point after the tag.
2620  *          On failure (i.e. when the tag wasn't the expected tag
2621  *          (TestGroup, TestElement) the internal file pointer
2622  *          \ref gdcmDocument::Fp is restored to it's original position.
2623  * @param   testGroup   The expected group of the tag.
2624  * @param   testElement The expected Element of the tag.
2625  * @return  True on success, false otherwise.
2626  */
2627 bool gdcmDocument::ReadTag(uint16_t testGroup, uint16_t testElement)
2628 {
2629    long positionOnEntry = ftell(Fp);
2630    long currentPosition = ftell(Fp);          // On debugging purposes
2631
2632    //// Read the Item Tag group and element, and make
2633    // sure they are what we expected:
2634    uint16_t itemTagGroup   = ReadInt16();
2635    uint16_t itemTagElement = ReadInt16();
2636    if ( itemTagGroup != testGroup || itemTagElement != testElement )
2637    {
2638       std::ostringstream s;
2639       s << "   We should have found tag (";
2640       s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2641       s << "   but instead we encountered tag (";
2642       s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2643         << std::endl;
2644       s << "  at address: " << (unsigned)currentPosition << std::endl;
2645       dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2646       dbg.Verbose(0, s.str().c_str());
2647       fseek(Fp, positionOnEntry, SEEK_SET);
2648
2649       return false;
2650    }
2651    return true;
2652 }
2653
2654 /**
2655  * \brief   Assuming the internal file pointer \ref gdcmDocument::Fp 
2656  *          is placed at the beginning of a tag (TestGroup, TestElement),
2657  *          read the length associated to the Tag.
2658  * \warning On success the internal file pointer \ref gdcmDocument::Fp
2659  *          is modified to point after the tag and it's length.
2660  *          On failure (i.e. when the tag wasn't the expected tag
2661  *          (TestGroup, TestElement) the internal file pointer
2662  *          \ref gdcmDocument::Fp is restored to it's original position.
2663  * @param   testGroup   The expected group of the tag.
2664  * @param   testElement The expected Element of the tag.
2665  * @return  On success returns the length associated to the tag. On failure
2666  *          returns 0.
2667  */
2668 uint32_t gdcmDocument::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2669 {
2670    long positionOnEntry = ftell(Fp);
2671    (void)positionOnEntry;
2672
2673    if ( !ReadTag(testGroup, testElement) )
2674    {
2675       return 0;
2676    }
2677                                                                                 
2678    //// Then read the associated Item Length
2679    long currentPosition = ftell(Fp);
2680    uint32_t itemLength  = ReadInt32();
2681    {
2682       std::ostringstream s;
2683       s << "Basic Item Length is: "
2684         << itemLength << std::endl;
2685       s << "  at address: " << (unsigned)currentPosition << std::endl;
2686       dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2687    }
2688    return itemLength;
2689 }
2690
2691 /**
2692  * \brief   Parse pixel data from disk for multi-fragment Jpeg/Rle files
2693  *          No other way so 'skip' the Data
2694  *
2695  */
2696 void gdcmDocument::Parse7FE0 ()
2697 {
2698    gdcmDocEntry* element = GetDocEntryByNumber(0x0002, 0x0010);
2699    if ( !element )
2700    {
2701       // Should warn user FIXME
2702       return;
2703    }
2704       
2705    if (   IsImplicitVRLittleEndianTransferSyntax()
2706        || IsExplicitVRLittleEndianTransferSyntax()
2707        || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2708        || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2709    {
2710       return;
2711    }
2712
2713    // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels 
2714
2715    //// Read the Basic Offset Table Item Tag length...
2716    uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2717
2718    //// ... and then read length[s] itself[themselves]. We don't use
2719    // the values read (BTW  what is the purpous of those lengths ?)
2720    if ( itemLength != 0 )
2721    {
2722       // BTW, what is the purpous of those length anyhow !? 
2723       char* basicOffsetTableItemValue = new char[itemLength + 1];
2724       fread(basicOffsetTableItemValue, itemLength, 1, Fp);
2725
2726       for (unsigned int i=0; i < itemLength; i += 4 )
2727       {
2728          uint32_t individualLength = str2num(&basicOffsetTableItemValue[i],uint32_t);
2729          std::ostringstream s;
2730          s << "   Read one length: ";
2731          s << std::hex << individualLength << std::endl;
2732          dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2733       }
2734       delete[] basicOffsetTableItemValue;
2735    }
2736
2737    if ( ! IsRLELossLessTransferSyntax() )
2738    {
2739       // JPEG Image
2740       
2741       //// We then skip (not reading them) all the fragments of images:
2742       while ( (itemLength = ReadTagLength(0xfffe, 0xe000)) )
2743       {
2744          SkipBytes(itemLength);
2745       }
2746    }
2747    else
2748    {
2749       // RLE Image
2750       long ftellRes;
2751       long rleSegmentLength[15], fragmentLength;
2752
2753       // While we find some items:
2754       while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2755       { 
2756          // Parse fragments of the current Fragment (Frame)    
2757          //------------------ scanning (not reading) fragment pixels
2758          uint32_t nbRleSegments = ReadInt32();
2759  
2760          //// Reading RLE Segments Offset Table
2761          uint32_t rleSegmentOffsetTable[15];
2762          for(int k=1; k<=15; k++)
2763          {
2764             ftellRes = ftell(Fp);
2765             rleSegmentOffsetTable[k] = ReadInt32();
2766          }
2767
2768          // skipping (not reading) RLE Segments
2769          if ( nbRleSegments > 1)
2770          {
2771             for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2772             {
2773                 rleSegmentLength[k] =  rleSegmentOffsetTable[k+1]
2774                                      - rleSegmentOffsetTable[k];
2775                 ftellRes = ftell(Fp);
2776                 SkipBytes(rleSegmentLength[k]);
2777              }
2778           }
2779
2780           rleSegmentLength[nbRleSegments] = fragmentLength 
2781                                           - rleSegmentOffsetTable[nbRleSegments];
2782           ftellRes = ftell(Fp);
2783           SkipBytes(rleSegmentLength[nbRleSegments]);
2784       }
2785
2786       // Make sure that at the end of the item we encounter a 'Sequence
2787       // Delimiter Item':
2788       if ( !ReadTag(0xfffe, 0xe0dd) )
2789       {
2790          dbg.Verbose(0, "gdcmDocument::Parse7FE0: no sequence delimiter item");
2791          dbg.Verbose(0, "    at end of RLE item sequence");
2792       }
2793    }
2794 }
2795
2796
2797
2798 /**
2799  * \brief   Compares two documents, according to \ref gdcmDicomDir rules
2800  * \warning Does NOT work with ACR-NEMA files
2801  * \todo    Find a trick to solve the pb (use RET fields ?)
2802  * @param   document
2803  * @return  true if 'smaller'
2804  */
2805 bool gdcmDocument::operator<(gdcmDocument &document)
2806 {
2807    // Patient Name
2808    std::string s1 = GetEntryByNumber(0x0010,0x0010);
2809    std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
2810    if(s1 < s2)
2811    {
2812       return true;
2813    }
2814    else if( s1 > s2 )
2815    {
2816       return false;
2817    }
2818    else
2819    {
2820       // Patient ID
2821       s1 = GetEntryByNumber(0x0010,0x0020);
2822       s2 = document.GetEntryByNumber(0x0010,0x0020);
2823       if ( s1 < s2 )
2824       {
2825          return true;
2826       }
2827       else if ( s1 > s2 )
2828       {
2829          return false;
2830       }
2831       else
2832       {
2833          // Study Instance UID
2834          s1 = GetEntryByNumber(0x0020,0x000d);
2835          s2 = document.GetEntryByNumber(0x0020,0x000d);
2836          if ( s1 < s2 )
2837          {
2838             return true;
2839          }
2840          else if( s1 > s2 )
2841          {
2842             return false;
2843          }
2844          else
2845          {
2846             // Serie Instance UID
2847             s1 = GetEntryByNumber(0x0020,0x000e);
2848             s2 = document.GetEntryByNumber(0x0020,0x000e);    
2849             if ( s1 < s2 )
2850             {
2851                return true;
2852             }
2853             else if( s1 > s2 )
2854             {
2855                return false;
2856             }
2857          }
2858       }
2859    }
2860    return false;
2861 }
2862
2863
2864 //-----------------------------------------------------------------------------