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