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