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