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