]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
remove tabs
[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 14:07:05 $
7   Version:   $Revision: 1.23 $
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 (/*!delim_mode && */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       //Entry->SetValue("gdcm::Skipped");
1327       // appel recursif de Load Value
1328       // (meme pb que pour le parsing)
1329       return;
1330    }
1331
1332    // When the length is zero things are easy:
1333    if ( length == 0 ) {
1334       ((gdcmValEntry *)Entry)->SetValue("");
1335       return;
1336    }
1337
1338    // The elements whose length is bigger than the specified upper bound
1339    // are not loaded. Instead we leave a short notice of the offset of
1340    // the element content and it's length.
1341    if (length > MaxSizeLoadEntry) {
1342       if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1343       {
1344          std::ostringstream s;
1345          s << "gdcm::NotLoaded.";
1346          s << " Address:" << (long)Entry->GetOffset();
1347          s << " Length:"  << Entry->GetLength();
1348          s << " x(" << std::hex << Entry->GetLength() << ")";
1349          ValEntryPtr->SetValue(s.str());
1350       }
1351       // to be sure we are at the end of the value ...
1352       fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1353       
1354       return;
1355    }
1356     
1357    // Any compacter code suggested (?)
1358    if ( IsDocEntryAnInteger(Entry) ) {   
1359       guint32 NewInt;
1360       std::ostringstream s;
1361       int nbInt;
1362    // When short integer(s) are expected, read and convert the following 
1363    // n *two characters properly i.e. as short integers as opposed to strings.
1364    // Elements with Value Multiplicity > 1
1365    // contain a set of integers (not a single one)       
1366       if (vr == "US" || vr == "SS") {
1367          nbInt = length / 2;
1368          NewInt = ReadInt16();
1369          s << NewInt;
1370          if (nbInt > 1){
1371             for (int i=1; i < nbInt; i++) {
1372                s << '\\';
1373                NewInt = ReadInt16();
1374                s << NewInt;
1375             }
1376          }
1377       }
1378    // When integer(s) are expected, read and convert the following 
1379    // n * four characters properly i.e. as integers as opposed to strings.
1380    // Elements with Value Multiplicity > 1
1381    // contain a set of integers (not a single one)           
1382       else if (vr == "UL" || vr == "SL") {
1383          nbInt = length / 4;
1384          NewInt = ReadInt32();
1385          s << NewInt;
1386          if (nbInt > 1) {
1387             for (int i=1; i < nbInt; i++) {
1388                s << '\\';
1389                NewInt = ReadInt32();
1390                s << NewInt;
1391             }
1392          }
1393       }
1394 #ifdef GDCM_NO_ANSI_STRING_STREAM
1395       s << std::ends; // to avoid oddities on Solaris
1396 #endif //GDCM_NO_ANSI_STRING_STREAM
1397
1398       ((gdcmValEntry *)Entry)->SetValue(s.str());
1399       return;
1400    }
1401    
1402    // We need an additional byte for storing \0 that is not on disk
1403    std::string NewValue(length,0);
1404    item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1405    if ( item_read != 1 ) {
1406       dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1407       ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1408       return;
1409    }
1410
1411    if( (vr == "UI") ) // Because of correspondance with the VR dic
1412       ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1413    else
1414       ((gdcmValEntry *)Entry)->SetValue(NewValue);
1415 }
1416
1417
1418 /**
1419  * \brief  Find the value Length of the passed Header Entry
1420  * @param  Entry Header Entry whose length of the value shall be loaded. 
1421  */
1422  void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1423    guint16 element = Entry->GetElement();
1424    //guint16 group   = Entry->GetGroup(); //FIXME
1425    std::string  vr = Entry->GetVR();
1426    guint16 length16;
1427        
1428    
1429    if ( (Filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) ) 
1430    {
1431       if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) 
1432       {
1433          // The following reserved two bytes (see PS 3.5-2001, section
1434          // 7.1.2 Data element structure with explicit vr p27) must be
1435          // skipped before proceeding on reading the length on 4 bytes.
1436          fseek(fp, 2L, SEEK_CUR);
1437          guint32 length32 = ReadInt32();
1438
1439          if ( (vr == "OB") && (length32 == 0xffffffff) ) 
1440          {
1441             Entry->SetLength(FindDocEntryLengthOB());
1442             return;
1443          }
1444          FixDocEntryFoundLength(Entry, length32); 
1445          return;
1446       }
1447
1448       // Length is encoded on 2 bytes.
1449       length16 = ReadInt16();
1450       
1451       // We can tell the current file is encoded in big endian (like
1452       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1453       // and it's value is the one of the encoding of a big endian file.
1454       // In order to deal with such big endian encoded files, we have
1455       // (at least) two strategies:
1456       // * when we load the "Transfer Syntax" tag with value of big endian
1457       //   encoding, we raise the proper flags. Then we wait for the end
1458       //   of the META group (0x0002) among which is "Transfer Syntax",
1459       //   before switching the swap code to big endian. We have to postpone
1460       //   the switching of the swap code since the META group is fully encoded
1461       //   in little endian, and big endian coding only starts at the next
1462       //   group. The corresponding code can be hard to analyse and adds
1463       //   many additional unnecessary tests for regular tags.
1464       // * the second strategy consists in waiting for trouble, that shall
1465       //   appear when we find the first group with big endian encoding. This
1466       //   is easy to detect since the length of a "Group Length" tag (the
1467       //   ones with zero as element number) has to be of 4 (0x0004). When we
1468       //   encounter 1024 (0x0400) chances are the encoding changed and we
1469       //   found a group with big endian encoding.
1470       // We shall use this second strategy. In order to make sure that we
1471       // can interpret the presence of an apparently big endian encoded
1472       // length of a "Group Length" without committing a big mistake, we
1473       // add an additional check: we look in the already parsed elements
1474       // for the presence of a "Transfer Syntax" whose value has to be "big
1475       // endian encoding". When this is the case, chances are we have got our
1476       // hands on a big endian encoded file: we switch the swap code to
1477       // big endian and proceed...
1478       if ( (element  == 0x0000) && (length16 == 0x0400) ) 
1479       {
1480          if ( ! IsExplicitVRBigEndianTransferSyntax() ) 
1481          {
1482             dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1483             errno = 1;
1484             return;
1485          }
1486          length16 = 4;
1487          SwitchSwapToBigEndian();
1488          // Restore the unproperly loaded values i.e. the group, the element
1489          // and the dictionary entry depending on them.
1490          guint16 CorrectGroup   = SwapShort(Entry->GetGroup());
1491          guint16 CorrectElem    = SwapShort(Entry->GetElement());
1492          gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1493                                                        CorrectElem);
1494          if (!NewTag) 
1495          {
1496             // This correct tag is not in the dictionary. Create a new one.
1497             NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1498          }
1499          // FIXME this can create a memory leaks on the old entry that be
1500          // left unreferenced.
1501          Entry->SetDictEntry(NewTag);
1502       }
1503        
1504       // Heuristic: well some files are really ill-formed.
1505       if ( length16 == 0xffff) 
1506       {
1507          length16 = 0;
1508          //dbg.Verbose(0, "gdcmDocument::FindLength",
1509          //            "Erroneous element length fixed.");
1510          // Actually, length= 0xffff means that we deal with
1511          // Unknown Sequence Length 
1512       }
1513       FixDocEntryFoundLength(Entry, (guint32)length16);
1514       return;
1515    }
1516    else
1517    {
1518       // Either implicit VR or a non DICOM conformal (see note below) explicit
1519       // VR that ommited the VR of (at least) this element. Farts happen.
1520       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1521       // on Data elements "Implicit and Explicit VR Data Elements shall
1522       // not coexist in a Data Set and Data Sets nested within it".]
1523       // Length is on 4 bytes.
1524       
1525       FixDocEntryFoundLength(Entry, ReadInt32());
1526       return;
1527    }
1528 }
1529
1530 /**
1531  * \brief     Find the Value Representation of the current Dicom Element.
1532  * @param     Entry
1533  */
1534 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry) 
1535 {
1536    if (Filetype != gdcmExplicitVR)
1537       return;
1538
1539    char VR[3];
1540
1541    long PositionOnEntry = ftell(fp);
1542    // Warning: we believe this is explicit VR (Value Representation) because
1543    // we used a heuristic that found "UL" in the first tag. Alas this
1544    // doesn't guarantee that all the tags will be in explicit VR. In some
1545    // cases (see e-film filtered files) one finds implicit VR tags mixed
1546    // within an explicit VR file. Hence we make sure the present tag
1547    // is in explicit VR and try to fix things if it happens not to be
1548    // the case.
1549    
1550    (void)fread (&VR, (size_t)2,(size_t)1, fp);
1551    VR[2]=0;
1552    if(!CheckDocEntryVR(Entry,VR))
1553    {
1554       fseek(fp, PositionOnEntry, SEEK_SET);
1555       // When this element is known in the dictionary we shall use, e.g. for
1556       // the semantics (see the usage of IsAnInteger), the VR proposed by the
1557       // dictionary entry. Still we have to flag the element as implicit since
1558       // we know now our assumption on expliciteness is not furfilled.
1559       // avoid  .
1560       if ( Entry->IsVRUnknown() )
1561          Entry->SetVR("Implicit");
1562       Entry->SetImplicitVR();
1563    }
1564 }
1565
1566 /**
1567  * \brief     Check the correspondance between the VR of the header entry
1568  *            and the taken VR. If they are different, the header entry is 
1569  *            updated with the new VR.
1570  * @param     Entry Header Entry to check
1571  * @param     vr    Dicom Value Representation
1572  * @return    false if the VR is incorrect of if the VR isn't referenced
1573  *            otherwise, it returns true
1574 */
1575 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1576 {
1577    char msg[100]; // for sprintf
1578    bool RealExplicit = true;
1579
1580    // Assume we are reading a falsely explicit VR file i.e. we reached
1581    // a tag where we expect reading a VR but are in fact we read the
1582    // first to bytes of the length. Then we will interogate (through find)
1583    // the dicom_vr dictionary with oddities like "\004\0" which crashes
1584    // both GCC and VC++ implementations of the STL map. Hence when the
1585    // expected VR read happens to be non-ascii characters we consider
1586    // we hit falsely explicit VR tag.
1587
1588    if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1589       RealExplicit = false;
1590
1591    // CLEANME searching the dicom_vr at each occurence is expensive.
1592    // PostPone this test in an optional integrity check at the end
1593    // of parsing or only in debug mode.
1594    if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1595       RealExplicit= false;
1596
1597    if ( !RealExplicit ) 
1598    {
1599       // We thought this was explicit VR, but we end up with an
1600       // implicit VR tag. Let's backtrack.   
1601       sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n", 
1602                    Entry->GetGroup(),Entry->GetElement());
1603       dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1604       if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1605          gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1606                                    Entry->GetGroup(),Entry->GetElement(),
1607                                    "UL","FIXME","Group Length");
1608          Entry->SetDictEntry(NewEntry);     
1609       }
1610       return(false);
1611    }
1612
1613    if ( Entry->IsVRUnknown() ) 
1614    {
1615       // When not a dictionary entry, we can safely overwrite the VR.
1616       if (Entry->GetElement() == 0x0000) { // Group length is UL !
1617          Entry->SetVR("UL");
1618       } else {
1619          Entry->SetVR(vr);
1620       }
1621    }
1622    else if ( Entry->GetVR() != vr ) 
1623    {
1624       // The VR present in the file and the dictionary disagree. We assume
1625       // the file writer knew best and use the VR of the file. Since it would
1626       // be unwise to overwrite the VR of a dictionary (since it would
1627       // compromise it's next user), we need to clone the actual DictEntry
1628       // and change the VR for the read one.
1629       gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1630                                  Entry->GetGroup(),Entry->GetElement(),
1631                                  vr,"FIXME",Entry->GetName());
1632       Entry->SetDictEntry(NewEntry);
1633    }
1634    return(true); 
1635 }
1636
1637 /**
1638  * \brief   Get the transformed value of the header entry. The VR value 
1639  *          is used to define the transformation to operate on the value
1640  * \warning NOT end user intended method !
1641  * @param   Entry 
1642  * @return  Transformed entry value
1643  */
1644 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1645 {
1646    if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1647    {
1648       std::string val=((gdcmValEntry *)Entry)->GetValue();
1649       std::string vr=Entry->GetVR();
1650       guint32 length = Entry->GetLength();
1651       std::ostringstream s;
1652       int nbInt;
1653
1654    // When short integer(s) are expected, read and convert the following 
1655    // n * 2 bytes properly i.e. as a multivaluated strings
1656    // (each single value is separated fromthe next one by '\'
1657    // as usual for standard multivaluated filels
1658    // Elements with Value Multiplicity > 1
1659    // contain a set of short integers (not a single one) 
1660    
1661       if (vr == "US" || vr == "SS")
1662       {
1663          guint16 NewInt16;
1664
1665          nbInt = length / 2;
1666          for (int i=0; i < nbInt; i++) 
1667          {
1668             if(i!=0)
1669                s << '\\';
1670             NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1671             NewInt16 = SwapShort(NewInt16);
1672             s << NewInt16;
1673          }
1674       }
1675
1676    // When integer(s) are expected, read and convert the following 
1677    // n * 4 bytes properly i.e. as a multivaluated strings
1678    // (each single value is separated fromthe next one by '\'
1679    // as usual for standard multivaluated filels
1680    // Elements with Value Multiplicity > 1
1681    // contain a set of integers (not a single one) 
1682       else if (vr == "UL" || vr == "SL")
1683       {
1684          guint32 NewInt32;
1685
1686          nbInt = length / 4;
1687          for (int i=0; i < nbInt; i++) 
1688          {
1689             if(i!=0)
1690                s << '\\';
1691             NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1692                      ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1693             NewInt32=SwapLong(NewInt32);
1694             s << NewInt32;
1695          }
1696       }
1697 #ifdef GDCM_NO_ANSI_STRING_STREAM
1698       s << std::ends; // to avoid oddities on Solaris
1699 #endif //GDCM_NO_ANSI_STRING_STREAM
1700       return(s.str());
1701    }
1702
1703    return(((gdcmValEntry *)Entry)->GetValue());
1704 }
1705
1706 /**
1707  * \brief   Get the reverse transformed value of the header entry. The VR 
1708  *          value is used to define the reverse transformation to operate on
1709  *          the value
1710  * \warning NOT end user intended method !
1711  * @param   Entry 
1712  * @return  Reverse transformed entry value
1713  */
1714 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1715 {
1716    if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1717    {
1718       std::string vr=Entry->GetVR();
1719       std::ostringstream s;
1720       std::vector<std::string> tokens;
1721
1722       if (vr == "US" || vr == "SS") 
1723       {
1724          guint16 NewInt16;
1725
1726          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1727          Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1728          for (unsigned int i=0; i<tokens.size();i++) 
1729          {
1730             NewInt16 = atoi(tokens[i].c_str());
1731             s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1732          }
1733          tokens.clear();
1734       }
1735       if (vr == "UL" || vr == "SL") 
1736       {
1737          guint32 NewInt32;
1738
1739          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1740          Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1741          for (unsigned int i=0; i<tokens.size();i++) 
1742          {
1743             NewInt32 = atoi(tokens[i].c_str());
1744             s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1745                <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1746          }
1747          tokens.clear();
1748       }
1749
1750 #ifdef GDCM_NO_ANSI_STRING_STREAM
1751       s << std::ends; // to avoid oddities on Solaris
1752 #endif //GDCM_NO_ANSI_STRING_STREAM
1753       return(s.str());
1754    }
1755
1756    return(((gdcmValEntry *)Entry)->GetValue());
1757 }
1758
1759 /**
1760  * \brief   Skip a given Header Entry 
1761  * \warning NOT end user intended method !
1762  * @param   entry 
1763  */
1764 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry) 
1765 {
1766    SkipBytes(entry->GetLength());
1767 }
1768
1769 /**
1770  * \brief   Skips to the begining of the next Header Entry 
1771  * \warning NOT end user intended method !
1772  * @param   entry 
1773  */
1774 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry) 
1775 {
1776    (void)fseek(fp, (long)(entry->GetOffset()),     SEEK_SET);
1777    (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1778 }
1779
1780 /**
1781  * \brief   Loads the value for a a given VLEntry 
1782  * \warning NOT end user intended method !
1783  * @param   entry 
1784  */
1785 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry) 
1786 {
1787     //SkipBytes(entry->GetLength());
1788     LoadDocEntry(entry);
1789 }
1790 /**
1791  * \brief   When the length of an element value is obviously wrong (because
1792  *          the parser went Jabberwocky) one can hope improving things by
1793  *          applying some heuristics.
1794  */
1795 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
1796                                           guint32 FoundLength)
1797 {
1798    Entry->SetReadLength(FoundLength); // will be updated only if a bug is found        
1799    if ( FoundLength == 0xffffffff) {
1800       FoundLength = 0;
1801    }
1802    
1803    guint16 gr =Entry->GetGroup();
1804    guint16 el =Entry->GetElement(); 
1805      
1806    if (FoundLength%2) {
1807       std::ostringstream s;
1808       s << "Warning : Tag with uneven length "
1809         << FoundLength 
1810         <<  " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1811       dbg.Verbose(0, s.str().c_str());
1812    }
1813       
1814    //////// Fix for some naughty General Electric images.
1815    // Allthough not recent many such GE corrupted images are still present
1816    // on Creatis hard disks. Hence this fix shall remain when such images
1817    // are no longer in user (we are talking a few years, here)...
1818    // Note: XMedCom probably uses such a trick since it is able to read
1819    //       those pesky GE images ...
1820    if (FoundLength == 13) {  // Only happens for this length !
1821       if (   (Entry->GetGroup() != 0x0008)
1822           || (   (Entry->GetElement() != 0x0070)
1823               && (Entry->GetElement() != 0x0080) ) )
1824       {
1825          FoundLength = 10;
1826          Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1827       }
1828    }
1829
1830    //////// Fix for some brain-dead 'Leonardo' Siemens images.
1831    // Occurence of such images is quite low (unless one leaves close to a
1832    // 'Leonardo' source. Hence, one might consider commenting out the
1833    // following fix on efficiency reasons.
1834    else
1835    if (   (Entry->GetGroup() == 0x0009)
1836        && (   (Entry->GetElement() == 0x1113)
1837            || (Entry->GetElement() == 0x1114) ) )
1838    {
1839       FoundLength = 4;
1840       Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1841    } 
1842  
1843    //////// Deal with sequences, but only on users request:
1844    else
1845    if ( ( Entry->GetVR() == "SQ") && enableSequences)
1846    {
1847          FoundLength = 0;      // ReadLength is unchanged 
1848    } 
1849     
1850    //////// We encountered a 'delimiter' element i.e. a tag of the form 
1851    // "fffe|xxxx" which is just a marker. Delimiters length should not be
1852    // taken into account.
1853    else
1854    if(Entry->GetGroup() == 0xfffe)
1855    {    
1856      // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1857      // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1858      // causes extra troubles...
1859      if( Entry->GetElement() != 0x0000 )
1860      {
1861         FoundLength = 0;
1862      }
1863    } 
1864            
1865    Entry->SetUsableLength(FoundLength);
1866 }
1867
1868 /**
1869  * \brief   Apply some heuristics to predict whether the considered 
1870  *          element value contains/represents an integer or not.
1871  * @param   Entry The element value on which to apply the predicate.
1872  * @return  The result of the heuristical predicate.
1873  */
1874 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
1875    guint16 element = Entry->GetElement();
1876    guint16 group   = Entry->GetGroup();
1877    std::string  vr = Entry->GetVR();
1878    guint32 length  = Entry->GetLength();
1879
1880    // When we have some semantics on the element we just read, and if we
1881    // a priori know we are dealing with an integer, then we shall be
1882    // able to swap it's element value properly.
1883    if ( element == 0 )  // This is the group length of the group
1884    {  
1885       if (length == 4)
1886          return true;
1887       else 
1888       {
1889          // Allthough this should never happen, still some images have a
1890          // corrupted group length [e.g. have a glance at offset x(8336) of
1891          // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1892          // Since for dicom compliant and well behaved headers, the present
1893          // test is useless (and might even look a bit paranoid), when we
1894          // encounter such an ill-formed image, we simply display a warning
1895          // message and proceed on parsing (while crossing fingers).
1896          std::ostringstream s;
1897          int filePosition = ftell(fp);
1898          s << "Erroneous Group Length element length  on : (" \
1899            << std::hex << group << " , " << element 
1900            << ") -before- position x(" << filePosition << ")"
1901            << "lgt : " << length;
1902          dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
1903       }
1904    }
1905
1906    if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1907       return true;
1908    
1909    return false;
1910 }
1911
1912 /**
1913  * \brief  Find the Length till the next sequence delimiter
1914  * \warning NOT end user intended method !
1915  * @return 
1916  */
1917
1918  guint32 gdcmDocument::FindDocEntryLengthOB(void)  {
1919    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1920    guint16 g;
1921    guint16 n; 
1922    long PositionOnEntry = ftell(fp);
1923    bool FoundSequenceDelimiter = false;
1924    guint32 TotalLength = 0;
1925    guint32 ItemLength;
1926
1927    while ( ! FoundSequenceDelimiter) 
1928    {
1929       g = ReadInt16();
1930       n = ReadInt16();   
1931       if (errno == 1)
1932          return 0;
1933       TotalLength += 4;  // We even have to decount the group and element 
1934      
1935       if ( g != 0xfffe && g!=0xb00c ) //for bogus header  
1936       {
1937          char msg[100]; // for sprintf. Sorry
1938          sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1939          dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg); 
1940          errno = 1;
1941          return 0;
1942       }
1943       if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header 
1944          FoundSequenceDelimiter = true;
1945       else if ( n != 0xe000 )
1946       {
1947          char msg[100];  // for sprintf. Sorry
1948          sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1949                       n, g,n);
1950          dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
1951          errno = 1;
1952          return 0;
1953       }
1954       ItemLength = ReadInt32();
1955       TotalLength += ItemLength + 4;  // We add 4 bytes since we just read
1956                                       // the ItemLength with ReadInt32                                     
1957       SkipBytes(ItemLength);
1958    }
1959    fseek(fp, PositionOnEntry, SEEK_SET);
1960    return TotalLength;
1961 }
1962
1963 /**
1964  * \brief Reads a supposed to be 16 Bits integer
1965  *       (swaps it depending on processor endianity) 
1966  * @return read value
1967  */
1968 guint16 gdcmDocument::ReadInt16() {
1969    guint16 g;
1970    size_t item_read;
1971    item_read = fread (&g, (size_t)2,(size_t)1, fp);
1972    if ( item_read != 1 ) {
1973       if(ferror(fp)) 
1974          dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
1975       errno = 1;
1976       return 0;
1977    }
1978    errno = 0;
1979    g = SwapShort(g);   
1980    return g;
1981 }
1982
1983 /**
1984  * \brief  Reads a supposed to be 32 Bits integer
1985  *         (swaps it depending on processor endianity)  
1986  * @return read value
1987  */
1988 guint32 gdcmDocument::ReadInt32() {
1989    guint32 g;
1990    size_t item_read;
1991    item_read = fread (&g, (size_t)4,(size_t)1, fp);
1992    if ( item_read != 1 ) { 
1993      if(ferror(fp)) 
1994          dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");   
1995       errno = 1;
1996       return 0;
1997    }
1998    errno = 0;   
1999    g = SwapLong(g);
2000    return g;
2001 }
2002
2003 /**
2004  * \brief skips bytes inside the source file 
2005  * \warning NOT end user intended method !
2006  * @return 
2007  */
2008 void gdcmDocument::SkipBytes(guint32 NBytes) {
2009    //FIXME don't dump the returned value
2010    (void)fseek(fp, (long)NBytes, SEEK_CUR);
2011 }
2012
2013 /**
2014  * \brief Loads all the needed Dictionaries
2015  * \warning NOT end user intended method !   
2016  */
2017 void gdcmDocument::Initialise(void) 
2018 {
2019    RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2020    RefShaDict = NULL;
2021 }
2022
2023 /**
2024  * \brief   Discover what the swap code is (among little endian, big endian,
2025  *          bad little endian, bad big endian).
2026  *          sw is set
2027  * @return false when we are absolutely sure 
2028  *               it's neither ACR-NEMA nor DICOM
2029  *         true  when we hope ours assuptions are OK
2030  */
2031 bool gdcmDocument::CheckSwap() {
2032
2033    // The only guaranted way of finding the swap code is to find a
2034    // group tag since we know it's length has to be of four bytes i.e.
2035    // 0x00000004. Finding the swap code in then straigthforward. Trouble
2036    // occurs when we can't find such group...
2037    
2038    guint32  x=4;  // x : for ntohs
2039    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2040    guint32  s32;
2041    guint16  s16;
2042        
2043    int lgrLue;
2044    char *entCur;
2045    char deb[HEADER_LENGTH_TO_READ];
2046     
2047    // First, compare HostByteOrder and NetworkByteOrder in order to
2048    // determine if we shall need to swap bytes (i.e. the Endian type).
2049    if (x==ntohs(x))
2050       net2host = true;
2051    else
2052       net2host = false; 
2053          
2054    // The easiest case is the one of a DICOM header, since it possesses a
2055    // file preamble where it suffice to look for the string "DICM".
2056    lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2057    
2058    entCur = deb + 128;
2059    if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2060       dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2061       
2062       // Next, determine the value representation (VR). Let's skip to the
2063       // first element (0002, 0000) and check there if we find "UL" 
2064       // - or "OB" if the 1st one is (0002,0001) -,
2065       // in which case we (almost) know it is explicit VR.
2066       // WARNING: if it happens to be implicit VR then what we will read
2067       // is the length of the group. If this ascii representation of this
2068       // length happens to be "UL" then we shall believe it is explicit VR.
2069       // FIXME: in order to fix the above warning, we could read the next
2070       // element value (or a couple of elements values) in order to make
2071       // sure we are not commiting a big mistake.
2072       // We need to skip :
2073       // * the 128 bytes of File Preamble (often padded with zeroes),
2074       // * the 4 bytes of "DICM" string,
2075       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2076       // i.e. a total of  136 bytes.
2077       entCur = deb + 136;
2078      
2079       // FIXME : FIXME:
2080       // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2081       // but elem 0002,0010 (Transfert Syntax) tells us the file is
2082       // *Implicit* VR.  -and it is !- 
2083       
2084       if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2085           (memcmp(entCur, "OB", (size_t)2) == 0) ||
2086           (memcmp(entCur, "UI", (size_t)2) == 0) ||
2087           (memcmp(entCur, "CS", (size_t)2) == 0) )  // CS, to remove later
2088                                                     // when Write DCM *adds*
2089       // FIXME
2090       // Use gdcmDocument::dicom_vr to test all the possibilities
2091       // instead of just checking for UL, OB and UI !? group 0000 
2092       {
2093          Filetype = gdcmExplicitVR;
2094          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2095                      "explicit Value Representation");
2096       } 
2097       else 
2098       {
2099          Filetype = gdcmImplicitVR;
2100          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2101                      "not an explicit Value Representation");
2102       }
2103       
2104       if (net2host) 
2105       {
2106          sw = 4321;
2107          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2108                         "HostByteOrder != NetworkByteOrder");
2109       } 
2110       else 
2111       {
2112          sw = 0;
2113          dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2114                         "HostByteOrder = NetworkByteOrder");
2115       }
2116       
2117       // Position the file position indicator at first tag (i.e.
2118       // after the file preamble and the "DICM" string).
2119       rewind(fp);
2120       fseek (fp, 132L, SEEK_SET);
2121       return true;
2122    } // End of DicomV3
2123
2124    // Alas, this is not a DicomV3 file and whatever happens there is no file
2125    // preamble. We can reset the file position indicator to where the data
2126    // is (i.e. the beginning of the file).
2127    dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2128    rewind(fp);
2129
2130    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2131    // By clean we mean that the length of the first tag is written down.
2132    // If this is the case and since the length of the first group HAS to be
2133    // four (bytes), then determining the proper swap code is straightforward.
2134
2135    entCur = deb + 4;
2136    // We assume the array of char we are considering contains the binary
2137    // representation of a 32 bits integer. Hence the following dirty
2138    // trick :
2139    s32 = *((guint32 *)(entCur));
2140       
2141    switch (s32) {
2142       case 0x00040000 :
2143          sw = 3412;
2144          Filetype = gdcmACR;
2145          return true;
2146       case 0x04000000 :
2147          sw = 4321;
2148          Filetype = gdcmACR;
2149          return true;
2150       case 0x00000400 :
2151          sw = 2143;
2152          Filetype = gdcmACR;
2153          return true;
2154       case 0x00000004 :
2155          sw = 0;
2156          Filetype = gdcmACR;
2157          return true;
2158       default :
2159
2160       // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2161       // It is time for despaired wild guesses. 
2162       // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2163       //  i.e. the 'group length' element is not present :     
2164       
2165       //  check the supposed to be 'group number'
2166       //  0x0002 or 0x0004 or 0x0008
2167       //  to determine ' sw' value .
2168       //  Only 0 or 4321 will be possible 
2169       //  (no oportunity to check for the formerly well known
2170       //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
2171       //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-) 
2172       //  the file IS NOT ACR-NEMA nor DICOM V3
2173       //  Find a trick to tell it the caller...
2174       
2175       s16 = *((guint16 *)(deb));
2176       
2177       switch (s16) {
2178       case 0x0002 :
2179       case 0x0004 :
2180       case 0x0008 :      
2181          sw = 0;
2182          Filetype = gdcmACR;
2183          return true;
2184       case 0x0200 :
2185       case 0x0400 :
2186       case 0x0800 : 
2187          sw = 4321;
2188          Filetype = gdcmACR;
2189          return true;
2190       default :
2191          dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2192                      "ACR/NEMA unfound swap info (Really hopeless !)"); 
2193          Filetype = gdcmUnknown;     
2194          return false;
2195       }
2196       
2197       // Then the only info we have is the net2host one.
2198       //if (! net2host )
2199          //   sw = 0;
2200          //else
2201          //  sw = 4321;
2202          //return;
2203    }
2204 }
2205
2206 /**
2207  * \brief Restore the unproperly loaded values i.e. the group, the element
2208  *        and the dictionary entry depending on them. 
2209  */
2210 void gdcmDocument::SwitchSwapToBigEndian(void) 
2211 {
2212    dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2213                   "Switching to BigEndian mode.");
2214    if ( sw == 0    ) 
2215    {
2216       sw = 4321;
2217       return;
2218    }
2219    if ( sw == 4321 ) 
2220    {
2221       sw = 0;
2222       return;
2223    }
2224    if ( sw == 3412 ) 
2225    {
2226       sw = 2143;
2227       return;
2228    }
2229    if ( sw == 2143 )
2230       sw = 3412;
2231 }
2232
2233 /**
2234  * \brief  during parsing, Header Elements too long are not loaded in memory 
2235  * @param NewSize
2236  */
2237 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize) 
2238 {
2239    if (NewSize < 0)
2240       return;
2241    if ((guint32)NewSize >= (guint32)0xffffffff) 
2242    {
2243       MaxSizeLoadEntry = 0xffffffff;
2244       return;
2245    }
2246    MaxSizeLoadEntry = NewSize;
2247 }
2248
2249
2250 /**
2251  * \brief Header Elements too long will not be printed
2252  * \todo  See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE 
2253  * @param NewSize
2254  */
2255 void gdcmDocument::SetMaxSizePrintEntry(long NewSize) 
2256 {
2257    if (NewSize < 0)
2258       return;
2259    if ((guint32)NewSize >= (guint32)0xffffffff) 
2260    {
2261       MaxSizePrintEntry = 0xffffffff;
2262       return;
2263    }
2264    MaxSizePrintEntry = NewSize;
2265 }
2266
2267
2268
2269 /**
2270  * \brief   Read the next tag but WITHOUT loading it's value
2271  *          (read the 'Group Number', the 'Element Number',
2272  *           gets the Dict Entry
2273  *          gets the VR, gets the length, gets the offset value)
2274  * @return  On succes the newly created DocEntry, NULL on failure.      
2275  */
2276 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2277    guint16 g,n;
2278    gdcmDocEntry *NewEntry;
2279    g = ReadInt16();
2280    n = ReadInt16();
2281       
2282    if (errno == 1)
2283       // We reached the EOF (or an error occured) therefore 
2284       // header parsing has to be considered as finished.
2285       return (gdcmDocEntry *)0;
2286
2287    NewEntry = NewDocEntryByNumber(g, n);
2288    FindDocEntryVR(NewEntry);
2289    FindDocEntryLength(NewEntry);
2290
2291    if (errno == 1) {
2292       // Call it quits
2293       delete NewEntry;
2294       return NULL;
2295    }
2296    NewEntry->SetOffset(ftell(fp));  
2297    return NewEntry;
2298 }
2299
2300
2301 /**
2302  * \brief   Generate a free TagKey i.e. a TagKey that is not present
2303  *          in the TagHt dictionary.
2304  * @param   group The generated tag must belong to this group.  
2305  * @return  The element of tag with given group which is fee.
2306  */
2307 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group) 
2308 {
2309    for (guint32 elem = 0; elem < UINT32_MAX; elem++) 
2310    {
2311       TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2312       if (tagHT.count(key) == 0)
2313          return elem;
2314    }
2315    return UINT32_MAX;
2316 }
2317
2318
2319 /**
2320  * \brief   Assuming the internal file pointer \ref gdcmDocument::fp 
2321  *          is placed at the beginning of a tag (TestGroup, TestElement),
2322  *          read the length associated to the Tag.
2323  * \warning On success the internal file pointer \ref gdcmDocument::fp
2324  *          is modified to point after the tag and it's length.
2325  *          On failure (i.e. when the tag wasn't the expected tag
2326  *          (TestGroup, TestElement) the internal file pointer
2327  *          \ref gdcmDocument::fp is restored to it's original position.
2328  * @param   TestGroup   The expected group of the tag.
2329  * @param   TestElement The expected Element of the tag.
2330  * @return  On success returns the length associated to the tag. On failure
2331  *          returns 0.
2332  */
2333 guint32 gdcmDocument::ReadTagLength(guint16 TestGroup, guint16 TestElement)
2334 {
2335    guint16 ItemTagGroup;
2336    guint16 ItemTagElement; 
2337    long PositionOnEntry = ftell(fp);
2338    long CurrentPosition = ftell(fp);          // On debugging purposes
2339
2340    //// Read the Item Tag group and element, and make
2341    // sure they are respectively 0xfffe and 0xe000:
2342    ItemTagGroup   = ReadInt16();
2343    ItemTagElement = ReadInt16();
2344    if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2345    {
2346       std::ostringstream s;
2347       s << "   We should have found tag (";
2348       s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2349       s << "   but instead we encountered tag (";
2350       s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2351         << std::endl;
2352       s << "  at address: " << (unsigned)CurrentPosition << std::endl;
2353       dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2354       dbg.Verbose(0, s.str().c_str());
2355       fseek(fp, PositionOnEntry, SEEK_SET);
2356       return 0;
2357    }
2358                                                                                 
2359    //// Then read the associated Item Length
2360    CurrentPosition=ftell(fp);
2361    guint32 ItemLength;
2362    ItemLength = ReadInt32();
2363    {
2364       std::ostringstream s;
2365       s << "Basic Item Length is: "
2366         << ItemLength << std::endl;
2367       s << "  at address: " << (unsigned)CurrentPosition << std::endl;
2368       dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2369    }
2370    return ItemLength;
2371 }
2372
2373 /**
2374  * \brief   Read the length of an exptected Item tag i.e. (0xfffe, 0xe000).
2375  * \sa      \ref gdcmDocument::ReadTagLength
2376  * \warning See warning of \ref gdcmDocument::ReadTagLength
2377  * @return  On success returns the length associated to the item tag.
2378  *          On failure returns 0.
2379  */ 
2380 guint32 gdcmDocument::ReadItemTagLength(void)
2381 {
2382    return ReadTagLength(0xfffe, 0xe000);
2383 }
2384
2385 /**
2386  * \brief   Read the length of an expected Sequence Delimiter tag i.e.
2387  *          (0xfffe, 0xe0dd).
2388  * \sa      \ref gdcmDocument::ReadTagLength
2389  * \warning See warning of \ref gdcmDocument::ReadTagLength
2390  * @return  On success returns the length associated to the Sequence
2391  *          Delimiter tag. On failure returns 0.
2392  */
2393 guint32 gdcmDocument::ReadSequenceDelimiterTagLength(void)
2394 {
2395    return ReadTagLength(0xfffe, 0xe0dd);
2396 }
2397
2398
2399 /**
2400  * \brief   Parse pixel data from disk for multi-fragment Jpeg/Rle files
2401  *          No other way so 'skip' the Data
2402  *
2403  */
2404
2405 void gdcmDocument::Parse7FE0 (void)
2406 {
2407    gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2408    if ( !Element )
2409       return;
2410       
2411    if (   IsImplicitVRLittleEndianTransferSyntax()
2412        || IsExplicitVRLittleEndianTransferSyntax()
2413        || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2414        || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2415       return;
2416       
2417    // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels 
2418
2419    //// Read the Basic Offset Table Item Tag length...
2420    guint32 ItemLength = ReadItemTagLength();
2421
2422    //// ... and then read length[s] itself[themselves]. We don't use
2423    // the values read (BTW  what is the purpous of those lengths ?)
2424    if (ItemLength != 0) {
2425       // BTW, what is the purpous of those length anyhow !? 
2426       char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2427       fread(BasicOffsetTableItemValue, ItemLength, 1, fp); 
2428       for (unsigned int i=0; i < ItemLength; i += 4){
2429          guint32 IndividualLength;
2430          IndividualLength = str2num(&BasicOffsetTableItemValue[i],guint32);
2431          std::ostringstream s;
2432          s << "   Read one length: ";
2433          s << std::hex << IndividualLength << std::endl;
2434          dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2435       }              
2436    }
2437
2438    if ( ! IsRLELossLessTransferSyntax() )
2439    {
2440       // JPEG Image
2441       
2442       //// We then skip (not reading them) all the fragments of images:
2443       while ( (ItemLength = ReadItemTagLength()) )
2444       {
2445          SkipBytes(ItemLength);
2446       } 
2447
2448    }
2449    else
2450    {
2451       // RLE Image
2452       long ftellRes;
2453       long RleSegmentLength[15], fragmentLength;
2454
2455       // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2456       while ( (fragmentLength = ReadSequenceDelimiterTagLength()) )
2457       { 
2458          // Parse fragments of the current Fragment (Frame)    
2459          //------------------ scanning (not reading) fragment pixels
2460          guint32 nbRleSegments = ReadInt32();
2461          printf("   Nb of RLE Segments : %d\n",nbRleSegments);
2462  
2463          //// Reading RLE Segments Offset Table
2464          guint32 RleSegmentOffsetTable[15];
2465          for(int k=1; k<=15; k++) {
2466             ftellRes=ftell(fp);
2467             RleSegmentOffsetTable[k] = ReadInt32();
2468             printf("        at : %x Offset Segment %d : %d (%x)\n",
2469                     (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2470                     RleSegmentOffsetTable[k]);
2471          }
2472
2473          // skipping (not reading) RLE Segments
2474          if (nbRleSegments>1) {
2475             for(unsigned int k=1; k<=nbRleSegments-1; k++) { 
2476                 RleSegmentLength[k]=   RleSegmentOffsetTable[k+1]
2477                                      - RleSegmentOffsetTable[k];
2478                 ftellRes=ftell(fp);
2479                 printf ("  Segment %d : Length = %d x(%x) Start at %x\n",
2480                         k,(unsigned)RleSegmentLength[k],
2481                        (unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2482                 SkipBytes(RleSegmentLength[k]);    
2483              }
2484           }
2485
2486           RleSegmentLength[nbRleSegments]= fragmentLength 
2487                                          - RleSegmentOffsetTable[nbRleSegments];
2488           ftellRes=ftell(fp);
2489           printf ("  Segment %d : Length = %d x(%x) Start at %x\n",
2490                   nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2491                   (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2492           SkipBytes(RleSegmentLength[nbRleSegments]); 
2493       } 
2494    }
2495 }
2496
2497
2498
2499 /**
2500  * \brief   Compares two documents, according to \ref gdcmDicomDir rules
2501  * \warning Does NOT work with ACR-NEMA files
2502  * \todo    Find a trick to solve the pb (use RET fields ?)
2503  * @param   document
2504  * @return  true if 'smaller'
2505  */
2506 bool gdcmDocument::operator<(gdcmDocument &document)
2507 {
2508    std::string s1,s2;
2509                                                                                 
2510    // Patient Name
2511    s1=this->GetEntryByNumber(0x0010,0x0010);
2512    s2=document.GetEntryByNumber(0x0010,0x0010);
2513    if(s1 < s2)
2514       return true;
2515    else if(s1 > s2)
2516       return false;
2517    else
2518    {
2519       // Patient ID
2520       s1=this->GetEntryByNumber(0x0010,0x0020);
2521       s2=document.GetEntryByNumber(0x0010,0x0020);
2522       if (s1 < s2)
2523          return true;
2524       else if (s1 > s2)
2525          return true;
2526       else
2527       {
2528          // Study Instance UID
2529          s1=this->GetEntryByNumber(0x0020,0x000d);
2530          s2=document.GetEntryByNumber(0x0020,0x000d);
2531          if (s1 < s2)
2532             return true;
2533          else if(s1 > s2)
2534             return false;
2535          else
2536          {
2537             // Serie Instance UID
2538             s1=this->GetEntryByNumber(0x0020,0x000e);
2539             s2=document.GetEntryByNumber(0x0020,0x000e);
2540             if (s1 < s2)
2541                return true;
2542             else if(s1 > s2)
2543                return false;
2544          }
2545       }
2546    }
2547    return false;
2548 }
2549
2550
2551 //-----------------------------------------------------------------------------