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