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