]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
Should leave gdcm::Document constructor in a much quicker
[gdcm.git] / src / gdcmDocument.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDocument.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/04/26 16:18:23 $
7   Version:   $Revision: 1.237 $
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 #include "gdcmTS.h"
27 #include "gdcmDictSet.h"
28 #include "gdcmDocEntrySet.h"
29 #include "gdcmSQItem.h"
30
31 #include <vector>
32 #include <iomanip>
33 #include <fstream>
34
35 namespace gdcm 
36 {
37 //-----------------------------------------------------------------------------
38 // Refer to Document::CheckSwap()
39 //const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
40
41 // Refer to Document::SetMaxSizeLoadEntry()
42 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
43
44 //-----------------------------------------------------------------------------
45 // Constructor / Destructor
46 // Constructors and destructors are protected to avoid user to invoke directly
47
48 /**
49  * \brief This default constructor neither loads nor parses the file. 
50  *        You should then invoke \ref Document::Load.
51  *         
52  */
53 Document::Document() 
54          :ElementSet(-1)
55 {
56    Fp = 0;
57
58    SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
59    Initialize();
60    SwapCode = 1234;
61    Filetype = ExplicitVR;
62    // Load will set it to true if sucessfull
63    Group0002Parsed = false;
64    IsDocumentAlreadyLoaded = false;
65    LoadMode = 0x00000000; // default : load everything, later
66 }
67
68 /**
69  * \brief   Constructor (not to break the API) 
70  * @param   filename 'Document' (File or DicomDir) to be opened for parsing
71  */
72 Document::Document( std::string const &filename )
73          :ElementSet(-1) 
74 {
75    Fp = 0;
76
77    SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
78    Initialize();
79    SwapCode = 1234;
80    Filetype = ExplicitVR;
81    Group0002Parsed = false;
82    LoadMode = 0x00000000; // Load everything
83
84    // Load will set it to true if sucessfull
85    IsDocumentAlreadyLoaded = false;
86
87    Load(filename); 
88 }
89 /**
90  * \brief   Canonical destructor.
91  */
92 Document::~Document ()
93 {
94    RefPubDict = NULL;
95    RefShaDict = NULL;
96 }
97
98 //-----------------------------------------------------------------------------
99 // Public
100
101 /**
102  * \brief   Loader  
103  * @param   filename 'Document' (File or DicomDir) to be opened for parsing
104  */
105 void Document::Load( std::string const &filename ) 
106 {
107    // We should clean out anything that already exists.
108    // Check IsDocumentAlreadyLoaded to be sure.
109    if( IsDocumentAlreadyLoaded )
110    {
111       gdcmWarningMacro( "A file was already parsed inside this " <<
112                    "gdcm::Document (previous name was: "
113                     << Filename.c_str() << ". New name is :"
114                     << filename );
115      // todo : clean out the 'Document'
116      // We should call ClearEntry() on the parent object ?!?
117    }
118
119    Filename = filename;
120
121    Fp = 0;
122    if ( !OpenFile() )
123    {
124       // warning already performed in OpenFile()
125       //gdcmWarningMacro( "Unable to open as an ACR/DICOM file: "
126       //                 << Filename.c_str() );
127       Filetype = Unknown;
128       return;
129    }
130
131    Group0002Parsed = false;
132
133    gdcmWarningMacro( "Starting parsing of file: " << Filename.c_str());
134
135    Fp->seekg(0, std::ios::end);
136    long lgt = Fp->tellg();       // total length of the file
137
138    Fp->seekg(0, std::ios::beg);
139
140    // CheckSwap returns a boolean 
141    // (false if no swap info of any kind was found)
142    if (! CheckSwap() )
143    {
144       gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: " 
145                    << Filename.c_str());
146       CloseFile(); 
147       return ;      
148     }
149
150    long beg = Fp->tellg();      // just after DICOM preamble (if any)
151
152    lgt -= beg;                  // remaining length to parse    
153
154    ParseDES( this, beg, lgt, false); // Loading is done during parsing
155
156    if ( IsEmpty() )
157    { 
158       gdcmWarningMacro( "No tag in internal hash table for: "
159                         << Filename.c_str());
160       CloseFile(); 
161       return ;
162    }
163    IsDocumentAlreadyLoaded = true;
164
165    Fp->seekg( 0, std::ios::beg);
166    
167    // Load 'non string' values
168       
169    std::string PhotometricInterpretation = GetEntryValue(0x0028,0x0004);   
170    if( PhotometricInterpretation == "PALETTE COLOR " )
171    {
172       LoadEntryBinArea(0x0028,0x1200);  // gray LUT   
173       /// FIXME FIXME FIXME
174       /// The tags refered by the three following lines used to be CORRECTLY
175       /// defined as having an US Value Representation in the public
176       /// dictionary. BUT the semantics implied by the three following
177       /// lines state that the corresponding tag contents are in fact
178       /// the ones of a BinEntry.
179       /// In order to fix things "Quick and Dirty" the dictionary was
180       /// altered on PURPOSE but now contains a WRONG value.
181       /// In order to fix things and restore the dictionary to its
182       /// correct value, one needs to decided of the semantics by deciding
183       /// whether the following tags are either:
184       /// - multivaluated US, and hence loaded as ValEntry, but afterwards
185       ///   also used as BinEntry, which requires the proper conversion,
186       /// - OW, and hence loaded as BinEntry, but afterwards also used
187       ///   as ValEntry, which requires the proper conversion.
188       LoadEntryBinArea(0x0028,0x1201);  // R    LUT
189       LoadEntryBinArea(0x0028,0x1202);  // G    LUT
190       LoadEntryBinArea(0x0028,0x1203);  // B    LUT
191       
192       // Segmented Red   Palette Color LUT Data
193       LoadEntryBinArea(0x0028,0x1221);
194       // Segmented Green Palette Color LUT Data
195       LoadEntryBinArea(0x0028,0x1222);
196       // Segmented Blue  Palette Color LUT Data
197       LoadEntryBinArea(0x0028,0x1223);
198    } 
199    //FIXME later : how to use it?
200    LoadEntryBinArea(0x0028,0x3006);  //LUT Data (CTX dependent) 
201
202    CloseFile(); 
203   
204    // ----------------------------
205    // Specific code to allow gdcm to read ACR-LibIDO formated images
206    // Note: ACR-LibIDO is an extension of the ACR standard that was
207    //       used at CREATIS. For the time being (say a couple years)
208    //       we keep this kludge to allow CREATIS users 
209    //       reading their old images.
210    //
211    // if recognition code tells us we deal with a LibIDO image
212    // we switch lineNumber and columnNumber
213    //
214    std::string RecCode;
215    RecCode = GetEntryValue(0x0008, 0x0010); // recognition code (RET)
216    if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
217        RecCode == "CANRME_AILIBOD1_1." )  // for brain-damaged softwares
218                                           // with "little-endian strings"
219    {
220          Filetype = ACR_LIBIDO; 
221          std::string rows    = GetEntryValue(0x0028, 0x0010);
222          std::string columns = GetEntryValue(0x0028, 0x0011);
223          SetValEntry(columns, 0x0028, 0x0010);
224          SetValEntry(rows   , 0x0028, 0x0011);
225    }
226    // --- End of ACR-LibIDO kludge --- 
227 }
228
229 /**
230  * \brief   Get the public dictionary used
231  */
232 Dict *Document::GetPubDict()
233 {
234    return RefPubDict;
235 }
236
237 /**
238  * \brief   Get the shadow dictionary used
239  */
240 Dict *Document::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 Document::SetShaDict(Dict *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 Document::SetShaDict(DictKey const &dictName)
260 {
261    RefShaDict = Global::GetDicts()->GetDict(dictName);
262    return !RefShaDict;
263 }
264
265 /**
266  * \brief  This predicate tells us whether or not the current Document 
267  *         was properly parsed and contains at least *one* Dicom Element
268  *         (and nothing more, sorry).
269  * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
270  *         true otherwise. 
271  */
272 bool Document::IsReadable()
273 {
274    if( Filetype == Unknown)
275    {
276       gdcmWarningMacro( "Wrong filetype");
277       return false;
278    }
279
280    if ( IsEmpty() )
281    { 
282       gdcmWarningMacro( "No tag in internal hash table.");
283       return false;
284    }
285
286    return true;
287 }
288
289 /**
290  * \brief   Predicate for dicom version 3 file.
291  * @return  True when the file is a dicom version 3.
292  */
293 bool Document::IsDicomV3()
294 {
295    // Checking if Transfer Syntax exists is enough
296    // Anyway, it's too late check if the 'Preamble' was found ...
297    // And ... would it be a rich idea to check ?
298    // (some 'no Preamble' DICOM images exist !)
299    return GetDocEntry(0x0002, 0x0010) != NULL;
300 }
301
302 /**
303  * \brief   Predicate for Papyrus file
304  *          Dedicated to whomsoever it may concern
305  * @return  True when the file is a Papyrus file.
306  */
307 bool Document::IsPapyrus()
308 {
309    // check for Papyrus private Sequence
310    DocEntry *e = GetDocEntry(0x0041, 0x1050);
311    if ( !e )
312       return false;
313    // check if it's actually a Sequence
314    if ( !dynamic_cast<SeqEntry*>(e) )
315       return  false;
316    return true;
317 }
318
319 /**
320  * \brief  returns the File Type 
321  *         (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
322  * @return the FileType code
323  */
324 FileType Document::GetFileType()
325 {
326    return Filetype;
327 }
328
329 /**
330  * \brief   Accessor to the Transfer Syntax (when present) of the
331  *          current document (it internally handles reading the
332  *          value from disk when only parsing occured).
333  * @return  The encountered Transfer Syntax of the current document.
334  */
335 std::string Document::GetTransferSyntax()
336 {
337    DocEntry *entry = GetDocEntry(0x0002, 0x0010);
338    if ( !entry )
339    {
340       return GDCM_UNKNOWN;
341    }
342
343    // The entry might be present but not loaded (parsing and loading
344    // happen at different stages): try loading and proceed with check...
345    LoadDocEntrySafe(entry);
346    if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
347    {
348       std::string transfer = valEntry->GetValue();
349       // The actual transfer (as read from disk) might be padded. We
350       // first need to remove the potential padding. We can make the
351       // weak assumption that padding was not executed with digits...
352       if  ( transfer.length() == 0 )
353       {
354          // for brain damaged headers
355          return GDCM_UNKNOWN;
356       }
357       while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
358       {
359          transfer.erase(transfer.length()-1, 1);
360       }
361       return transfer;
362    }
363    return GDCM_UNKNOWN;
364 }
365
366 /**
367  * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
368  * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
369  */
370 std::string Document::GetTransferSyntaxName()
371 {
372    // use the TS (TS : Transfer Syntax)
373    std::string transferSyntax = GetEntryValue(0x0002,0x0010);
374
375    if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
376    {
377       gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
378                << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
379       return "Uncompressed ACR-NEMA";
380    }
381    if ( transferSyntax == GDCM_UNFOUND )
382    {
383       gdcmWarningMacro( "Unfound Transfer Syntax (0002,0010)");
384       return "Uncompressed ACR-NEMA";
385    }
386
387    // we do it only when we need it
388    const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
389
390    // Global::GetTS() is a global static you shall never try to delete it!
391    return tsName;
392 }
393 //
394 // --------------- Swap Code ------------------
395 /**
396  * \brief   Swaps the bytes so they agree with the processor order
397  * @return  The properly swaped 16 bits integer.
398  */
399 uint16_t Document::SwapShort(uint16_t a)
400 {
401    if ( SwapCode == 4321 || SwapCode == 2143 )
402    {
403       //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
404       // Save CPU time
405       a = ( a << 8 ) | ( a >> 8 );
406    }
407    return a;
408 }
409
410 /**
411  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
412  *          processor order.
413  * @return  The properly swaped 32 bits integer.
414  */
415 uint32_t Document::SwapLong(uint32_t a)
416 {
417    switch (SwapCode)
418    {
419       case 1234 :
420          break;
421       case 4321 :
422 //         a=( ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000) | 
423 //             ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
424 // save CPU time
425          a=( ( a<<24)               | ((a<<8)  & 0x00ff0000) | 
426              ((a>>8)  & 0x0000ff00) |  (a>>24)                );
427          break;   
428       case 3412 :
429 //       a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
430          a=( (a<<16)                | (a>>16)  );
431          break;  
432       case 2143 :
433          a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
434       break;
435       default :
436          gdcmErrorMacro( "Unset swap code:" << SwapCode );
437          a = 0;
438    }
439    return a;
440
441
442 //
443 // -----------------File I/O ---------------
444 /**
445  * \brief  Tries to open the file \ref Document::Filename and
446  *         checks the preamble when existing.
447  * @return The FILE pointer on success. 
448  */
449 std::ifstream *Document::OpenFile()
450 {
451    HasDCMPreamble = false;
452    if (Filename.length() == 0) 
453    {
454       return 0;
455    }
456
457    if(Fp)
458    {
459       gdcmWarningMacro( "File already open: " << Filename.c_str());
460       CloseFile();
461    }
462
463    Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
464    if( ! *Fp )
465    {
466       gdcmErrorMacro( "Cannot open file: " << Filename.c_str());
467       delete Fp;
468       Fp = 0;
469       return 0;
470       //exit(1); // No function is allowed to leave the application instead
471                  // of warning the caller
472    }
473  
474    uint16_t zero = 0;
475    Fp->read((char*)&zero, (size_t)2);
476    if( Fp->eof() )
477    {
478       CloseFile();
479       return 0;
480    }
481  
482    //-- ACR or DICOM with no Preamble; may start with a Shadow Group --
483    if( 
484        zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
485        zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
486        zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
487        zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
488    {
489       std::string msg = Util::Format(
490         "ACR/DICOM starting at the begining of the file:(%04x)\n", zero);
491       gdcmWarningMacro( msg.c_str() );
492       return Fp;
493    }
494  
495    //-- DICOM --
496    Fp->seekg(126L, std::ios::cur);
497    char dicm[4] = {' ',' ',' ',' '};
498    Fp->read(dicm,  (size_t)4);
499    if( Fp->eof() )
500    {
501       CloseFile();
502       return 0;
503    }
504    if( memcmp(dicm, "DICM", 4) == 0 )
505    {
506       HasDCMPreamble = true;
507       return Fp;
508    }
509
510    // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
511    CloseFile();
512    gdcmWarningMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
513                       << Filename.c_str()); 
514    return 0;
515 }
516
517 /**
518  * \brief closes the file  
519  * @return  TRUE if the close was successfull 
520  */
521 bool Document::CloseFile()
522 {
523    if( Fp )
524    {
525       Fp->close();
526       delete Fp;
527       Fp = 0;
528    }
529    return true;
530 }
531
532 /**
533  * \brief Writes in a file all the Header Entries (Dicom Elements) 
534  * @param fp file pointer on an already open file (actually: Output File Stream)
535  * @param filetype Type of the File to be written 
536  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
537  * @return Always true.
538  */
539 void Document::WriteContent(std::ofstream *fp, FileType filetype)
540 {
541    // \TODO move the following lines (and a lot of others, to be written)
542    // to a future function CheckAndCorrectHeader  
543
544    // (necessary if user wants to write a DICOM V3 file
545    // starting from an ACR-NEMA (V2) Header
546
547    if ( filetype == ImplicitVR || filetype == ExplicitVR )
548    {
549       // writing Dicom File Preamble
550       char filePreamble[128];
551       memset(filePreamble, 0, 128);
552       fp->write(filePreamble, 128);
553       fp->write("DICM", 4);
554    }
555
556    /*
557     * \todo rewrite later, if really usefull
558     *       - 'Group Length' element is optional in DICOM
559     *       - but un-updated odd groups lengthes can causes pb
560     *         (xmedcon breaker)
561     *
562     * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
563     *    UpdateGroupLength(false,filetype);
564     * if ( filetype == ACR)
565     *    UpdateGroupLength(true,ACR);
566     */
567
568    ElementSet::WriteContent(fp, filetype); // This one is recursive
569 }
570
571 // -----------------------------------------
572 // Content entries 
573 /**
574  * \brief Loads (from disk) the element content 
575  *        when a string is not suitable
576  * @param group   group number of the Entry 
577  * @param elem  element number of the Entry
578  */
579 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
580 {
581    // Search the corresponding DocEntry
582    DocEntry *docElement = GetDocEntry(group, elem);
583    if ( !docElement )
584       return;
585
586    BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
587    if( !binElement )
588       return;
589
590    LoadEntryBinArea(binElement);
591 }
592
593 /**
594  * \brief Loads (from disk) the element content 
595  *        when a string is not suitable
596  * @param elem  Entry whose binArea is going to be loaded
597  */
598 void Document::LoadEntryBinArea(BinEntry *elem) 
599 {
600    if(elem->GetBinArea())
601       return;
602
603    bool openFile = !Fp;
604    if(openFile)
605       OpenFile();
606
607    size_t o =(size_t)elem->GetOffset();
608    Fp->seekg(o, std::ios::beg);
609
610    size_t l = elem->GetLength();
611    uint8_t *a = new uint8_t[l];
612    if( !a )
613    {
614       gdcmWarningMacro( "Cannot allocate BinEntry content");
615       return;
616    }
617
618    Fp->read((char*)a, l);
619    if( Fp->fail() || Fp->eof())
620    {
621       delete[] a;
622       return;
623    }
624
625    elem->SetBinArea(a);
626
627    if(openFile)
628       CloseFile();
629 }
630
631 /**
632  * \brief  Loads the element while preserving the current
633  *         underlying file position indicator as opposed to
634  *        LoadDocEntry that modifies it.
635  * @param entry   DocEntry whose value will be loaded. 
636  */
637 void Document::LoadDocEntrySafe(DocEntry *entry)
638 {
639    if(Fp)
640    {
641       long PositionOnEntry = Fp->tellg();
642       LoadDocEntry(entry);
643       Fp->seekg(PositionOnEntry, std::ios::beg);
644    }
645 }
646
647 /**
648  * \brief   Compares two documents, according to \ref DicomDir rules
649  * \warning Does NOT work with ACR-NEMA files
650  * \todo    Find a trick to solve the pb (use RET fields ?)
651  * @param   document to compare with current one
652  * @return  true if 'smaller'
653  */
654 bool Document::operator<(Document &document)
655 {
656    // Patient Name
657    std::string s1 = GetEntryValue(0x0010,0x0010);
658    std::string s2 = document.GetEntryValue(0x0010,0x0010);
659    if(s1 < s2)
660    {
661       return true;
662    }
663    else if( s1 > s2 )
664    {
665       return false;
666    }
667    else
668    {
669       // Patient ID
670       s1 = GetEntryValue(0x0010,0x0020);
671       s2 = document.GetEntryValue(0x0010,0x0020);
672       if ( s1 < s2 )
673       {
674          return true;
675       }
676       else if ( s1 > s2 )
677       {
678          return false;
679       }
680       else
681       {
682          // Study Instance UID
683          s1 = GetEntryValue(0x0020,0x000d);
684          s2 = document.GetEntryValue(0x0020,0x000d);
685          if ( s1 < s2 )
686          {
687             return true;
688          }
689          else if( s1 > s2 )
690          {
691             return false;
692          }
693          else
694          {
695             // Serie Instance UID
696             s1 = GetEntryValue(0x0020,0x000e);
697             s2 = document.GetEntryValue(0x0020,0x000e);    
698             if ( s1 < s2 )
699             {
700                return true;
701             }
702             else if( s1 > s2 )
703             {
704                return false;
705             }
706          }
707       }
708    }
709    return false;
710 }
711
712 //-----------------------------------------------------------------------------
713 // Protected
714 /**
715  * \brief Reads a supposed to be 16 Bits integer
716  *       (swaps it depending on processor endianness) 
717  * @return read value
718  */
719 uint16_t Document::ReadInt16()
720    throw( FormatError )
721 {
722    uint16_t g;
723    Fp->read ((char*)&g, (size_t)2);
724    if ( Fp->fail() )
725    {
726       throw FormatError( "Document::ReadInt16()", " file error." );
727    }
728    if( Fp->eof() )
729    {
730       throw FormatError( "Document::ReadInt16()", "EOF." );
731    }
732    g = SwapShort(g); 
733    return g;
734 }
735
736 /**
737  * \brief  Reads a supposed to be 32 Bits integer
738  *        (swaps it depending on processor endianness)  
739  * @return read value
740  */
741 uint32_t Document::ReadInt32()
742    throw( FormatError )
743 {
744    uint32_t g;
745    Fp->read ((char*)&g, (size_t)4);
746    if ( Fp->fail() )
747    {
748       throw FormatError( "Document::ReadInt32()", " file error." );
749    }
750    if( Fp->eof() )
751    {
752       throw FormatError( "Document::ReadInt32()", "EOF." );
753    }
754    g = SwapLong(g);
755    return g;
756 }
757
758 /**
759  * \brief skips bytes inside the source file 
760  * \warning NOT end user intended method !
761  * @return 
762  */
763 void Document::SkipBytes(uint32_t nBytes)
764 {
765    //FIXME don't dump the returned value
766    Fp->seekg((long)nBytes, std::ios::cur);
767 }
768
769 /**
770  * \brief   Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
771  * @param filetype Type of the File to be written 
772  */
773 int Document::ComputeGroup0002Length( FileType filetype ) 
774 {
775    uint16_t gr;
776    std::string vr;
777    
778    int groupLength = 0;
779    bool found0002 = false;   
780   
781    // for each zero-level Tag in the DCM Header
782    DocEntry *entry = GetFirstEntry();
783    while( entry )
784    {
785       gr = entry->GetGroup();
786
787       if( gr == 0x0002 )
788       {
789          found0002 = true;
790
791          if( entry->GetElement() != 0x0000 )
792          {
793             vr = entry->GetVR();
794  
795             if( filetype == ExplicitVR )
796             {
797                if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ) 
798                {
799                   // explicit VR AND OB, OW, SQ : 4 more bytes
800                   groupLength +=  4;
801                }
802             }
803             groupLength += 2 + 2 + 4 + entry->GetLength();   
804          }
805       }
806       else if (found0002 )
807          break;
808
809       entry = GetNextEntry();
810    }
811    return groupLength; 
812 }
813
814 //-----------------------------------------------------------------------------
815 // Private
816 /**
817  * \brief Loads all the needed Dictionaries
818  * \warning NOT end user intended method !   
819  */
820 void Document::Initialize() 
821 {
822    RefPubDict = Global::GetDicts()->GetDefaultPubDict();
823    RefShaDict = NULL;
824    Filetype   = Unknown;
825 }
826
827 /**
828  * \brief   Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
829  * @param set DocEntrySet we are going to parse ('zero level'   or a SQItem)
830  * @param offset start of parsing
831  * @param l_max  length to parse
832  * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
833  */ 
834 void Document::ParseDES(DocEntrySet *set, long offset, 
835                         long l_max, bool delim_mode)
836 {
837    DocEntry *newDocEntry;
838    ValEntry *newValEntry;
839    BinEntry *newBinEntry;
840    SeqEntry *newSeqEntry;
841    VRKey vr;
842    bool used;
843
844    while (true)
845    {
846       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
847       {
848          break;
849       }
850
851       used = true;
852       newDocEntry = ReadNextDocEntry( );
853
854       if ( !newDocEntry )
855       {
856          break;
857       }
858
859       vr = newDocEntry->GetVR();
860       newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
861       newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
862       newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
863
864       if ( newValEntry || newBinEntry )
865       {
866          if ( newBinEntry )
867          {
868             if ( Filetype == ExplicitVR && 
869                  !Global::GetVR()->IsVROfBinaryRepresentable(vr) )
870             { 
871                 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
872                 gdcmWarningMacro( std::hex << newDocEntry->GetGroup() 
873                                   << "|" << newDocEntry->GetElement()
874                                   << " : Neither Valentry, nor BinEntry." 
875                                   "Probably unknown VR.");
876             }
877
878          //////////////////// BinEntry or UNKOWN VR:
879             // When "this" is a Document the Key is simply of the
880             // form ( group, elem )...
881             if ( dynamic_cast< Document* > ( set ) )
882             {
883                newBinEntry->SetKey( newBinEntry->GetKey() );
884             }
885             // but when "this" is a SQItem, we are inserting this new
886             // valEntry in a sequence item, and the key has the
887             // generalized form (refer to \ref BaseTagKey):
888             if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
889             {
890                newBinEntry->SetKey(  parentSQItem->GetBaseTagKey()
891                                    + newBinEntry->GetKey() );
892             }
893
894             LoadDocEntry( newBinEntry );
895             if( !set->AddEntry( newBinEntry ) )
896             {
897               //Expect big troubles if here
898               //delete newBinEntry;
899               used=false;
900             }
901          }
902          else
903          {
904          /////////////////////// ValEntry
905
906             // When "set" is a Document, then we are at the top of the
907             // hierarchy and the Key is simply of the form ( group, elem )...
908             if ( dynamic_cast< Document* > ( set ) )
909             {
910                newValEntry->SetKey( newValEntry->GetKey() );
911             }
912             // ...but when "set" is a SQItem, we are inserting this new
913             // valEntry in a sequence item. Hence the key has the
914             // generalized form (refer to \ref BaseTagKey):
915             if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
916             {
917                newValEntry->SetKey(  parentSQItem->GetBaseTagKey()
918                                    + newValEntry->GetKey() );
919             }
920              
921             LoadDocEntry( newValEntry );
922             bool delimitor=newValEntry->IsItemDelimitor();
923
924             if ( LoadMode & NO_SHADOW ) // User asked to skip, if possible, 
925                                         // shadow groups ( if possible :
926                                         // whether element 0x0000 exits)
927             {
928                if ( newValEntry->GetGroup()%2 != 0 )
929                {
930                   if ( newValEntry->GetElement() == 0x0000 )
931                   {
932                      std::string strLgrGroup = newValEntry->GetValue();
933                      int lgrGroup;
934                      if ( strLgrGroup != GDCM_UNFOUND)
935                      {
936                         lgrGroup = atoi(strLgrGroup.c_str());
937                         Fp->seekg(lgrGroup , std::ios::cur);
938                         used = false;
939                         continue;
940                      }
941                   }
942                }
943              }
944
945             if( !set->AddEntry( newValEntry ) )
946             {
947               // If here expect big troubles
948               // delete newValEntry; //otherwise mem leak
949               used=false;
950             }
951
952             if (delimitor)
953             {
954                if(!used)
955                   delete newDocEntry;
956                break;
957             }
958             if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
959             {
960                if(!used)
961                   delete newDocEntry;
962                break;
963             }
964          }
965
966          // Just to make sure we are at the beginning of next entry.
967          SkipToNextDocEntry(newDocEntry);
968       }
969       else
970       {
971          // VR = "SQ"
972          unsigned long l = newDocEntry->GetReadLength();          
973          if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
974          {
975             if ( l == 0xffffffff )
976             {
977               delim_mode = true;
978             }
979             else
980             {
981               delim_mode = false;
982             }
983          }
984  
985          if ( (LoadMode & NO_SEQ) && ! delim_mode ) // User asked to skip SQ
986          {
987             Fp->seekg( l, std::ios::cur);
988             used = false;
989             continue;
990           }
991          
992          // no other way to create it ...
993          newSeqEntry->SetDelimitorMode( delim_mode );
994
995          // At the top of the hierarchy, stands a Document. When "set"
996          // is a Document, then we are building the first depth level.
997          // Hence the SeqEntry we are building simply has a depth
998          // level of one:
999          if ( dynamic_cast< Document* > ( set ) )
1000          {
1001             newSeqEntry->SetDepthLevel( 1 );
1002             newSeqEntry->SetKey( newSeqEntry->GetKey() );
1003          }
1004          // But when "set" is already a SQItem, we are building a nested
1005          // sequence, and hence the depth level of the new SeqEntry
1006          // we are building, is one level deeper:
1007          if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1008          {
1009             newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1010             newSeqEntry->SetKey(  parentSQItem->GetBaseTagKey()
1011                                 + newSeqEntry->GetKey() );
1012          }
1013
1014          if ( l != 0 )
1015          {  // Don't try to parse zero-length sequences
1016             ParseSQ( newSeqEntry, 
1017                      newDocEntry->GetOffset(),
1018                      l, delim_mode);
1019          }
1020          if( !set->AddEntry( newSeqEntry ) )
1021          {
1022             used = false;
1023          }
1024
1025          if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1026          {
1027             if( !used )
1028                delete newDocEntry;
1029             break;
1030          }
1031       }
1032
1033       if( !used )
1034          delete newDocEntry;
1035    }
1036 }
1037
1038 /**
1039  * \brief   Parses a Sequence ( SeqEntry after SeqEntry)
1040  * @return  parsed length for this level
1041  */ 
1042 void Document::ParseSQ( SeqEntry *seqEntry,
1043                         long offset, long l_max, bool delim_mode)
1044 {
1045    int SQItemNumber = 0;
1046    bool dlm_mod;
1047    long offsetStartCurrentSQItem = offset;
1048
1049    while (true)
1050    {
1051       // the first time, we read the fff0,e000 of the first SQItem
1052       DocEntry *newDocEntry = ReadNextDocEntry();
1053
1054       if ( !newDocEntry )
1055       {
1056          // FIXME Should warn user
1057          break;
1058       }
1059       if( delim_mode )
1060       {
1061          if ( newDocEntry->IsSequenceDelimitor() )
1062          {
1063             seqEntry->SetDelimitationItem( newDocEntry ); 
1064             break;
1065          }
1066       }
1067       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1068       {
1069          delete newDocEntry;
1070          break;
1071       }
1072       // create the current SQItem
1073       SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1074       std::ostringstream newBase;
1075       newBase << seqEntry->GetKey()
1076               << "/"
1077               << SQItemNumber
1078               << "#";
1079       itemSQ->SetBaseTagKey( newBase.str() );
1080       unsigned int l = newDocEntry->GetReadLength();
1081       
1082       if ( l == 0xffffffff )
1083       {
1084          dlm_mod = true;
1085       }
1086       else
1087       {
1088          dlm_mod = false;
1089       }
1090
1091       // Let's try :------------
1092       // remove fff0,e000, created out of the SQItem
1093       delete newDocEntry;
1094       Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1095       // fill up the current SQItem, starting at the beginning of fff0,e000
1096       ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1097       offsetStartCurrentSQItem = Fp->tellg();
1098       // end try -----------------
1099  
1100       seqEntry->AddSQItem( itemSQ, SQItemNumber ); 
1101       SQItemNumber++;
1102       if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1103       {
1104          break;
1105       }
1106    }
1107 }
1108
1109 /**
1110  * \brief   Loads the element content if its length doesn't exceed
1111  *          the value specified with Document::SetMaxSizeLoadEntry()
1112  * @param   entry Header Entry (Dicom Element) to be dealt with
1113  */
1114 void Document::LoadDocEntry(DocEntry *entry)
1115 {
1116    uint16_t group  = entry->GetGroup();
1117    std::string  vr = entry->GetVR();
1118    uint32_t length = entry->GetLength();
1119
1120    Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1121
1122    // A SeQuence "contains" a set of Elements.  
1123    //          (fffe e000) tells us an Element is beginning
1124    //          (fffe e00d) tells us an Element just ended
1125    //          (fffe e0dd) tells us the current SeQuence just ended
1126    if( group == 0xfffe )
1127    {
1128       // NO more value field for SQ !
1129       return;
1130    }
1131
1132    // When the length is zero things are easy:
1133    if ( length == 0 )
1134    {
1135       ((ValEntry *)entry)->SetValue("");
1136       return;
1137    }
1138
1139    // The elements whose length is bigger than the specified upper bound
1140    // are not loaded. Instead we leave a short notice of the offset of
1141    // the element content and it's length.
1142
1143    std::ostringstream s;
1144    if (length > MaxSizeLoadEntry)
1145    {
1146       if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1147       {  
1148          //s << "gdcm::NotLoaded (BinEntry)";
1149          s << GDCM_NOTLOADED;
1150          s << " Ad.:" << (long)entry->GetOffset();
1151          s << " x(" << std::hex << entry->GetOffset() << ")";
1152          s << std::dec;
1153          s << " Lgt:"  << entry->GetLength();
1154          s << " x(" << std::hex << entry->GetLength() << ")";
1155          binEntryPtr->SetValue(s.str());
1156       }
1157       // Be carefull : a BinEntry IS_A ValEntry ... 
1158       else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1159       {
1160         // s << "gdcm::NotLoaded. (ValEntry)";
1161          s << GDCM_NOTLOADED;  
1162          s << " Address:" << (long)entry->GetOffset();
1163          s << " Length:"  << entry->GetLength();
1164          s << " x(" << std::hex << entry->GetLength() << ")";
1165          valEntryPtr->SetValue(s.str());
1166       }
1167       else
1168       {
1169          // fusible
1170          gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1171                       << "nor a ValEntry ?! Should never print that !" );
1172       }
1173
1174       // to be sure we are at the end of the value ...
1175       Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1176                 std::ios::beg);
1177       return;
1178    }
1179
1180    // When we find a BinEntry not very much can be done :
1181    if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1182    {
1183       s << GDCM_BINLOADED;
1184       binEntryPtr->SetValue(s.str());
1185       LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1186       return;
1187    }
1188
1189    if ( IsDocEntryAnInteger(entry) )
1190    {   
1191       uint32_t NewInt;
1192       int nbInt;
1193       // When short integer(s) are expected, read and convert the following 
1194       // n *two characters properly i.e. consider them as short integers as
1195       // opposed to strings.
1196       // Elements with Value Multiplicity > 1
1197       // contain a set of integers (not a single one)       
1198       if (vr == "US" || vr == "SS")
1199       {
1200          nbInt = length / 2;
1201          NewInt = ReadInt16();
1202          s << NewInt;
1203          if (nbInt > 1)
1204          {
1205             for (int i=1; i < nbInt; i++)
1206             {
1207                s << '\\';
1208                NewInt = ReadInt16();
1209                s << NewInt;
1210             }
1211          }
1212       }
1213       // See above comment on multiple integers (mutatis mutandis).
1214       else if (vr == "UL" || vr == "SL")
1215       {
1216          nbInt = length / 4;
1217          NewInt = ReadInt32();
1218          s << NewInt;
1219          if (nbInt > 1)
1220          {
1221             for (int i=1; i < nbInt; i++)
1222             {
1223                s << '\\';
1224                NewInt = ReadInt32();
1225                s << NewInt;
1226             }
1227          }
1228       }
1229 #ifdef GDCM_NO_ANSI_STRING_STREAM
1230       s << std::ends; // to avoid oddities on Solaris
1231 #endif //GDCM_NO_ANSI_STRING_STREAM
1232
1233       ((ValEntry *)entry)->SetValue(s.str());
1234       return;
1235    }
1236    
1237   // FIXME: We need an additional byte for storing \0 that is not on disk
1238    char *str = new char[length+1];
1239    Fp->read(str, (size_t)length);
1240    str[length] = '\0'; //this is only useful when length is odd
1241    // Special DicomString call to properly handle \0 and even length
1242    std::string newValue;
1243    if( length % 2 )
1244    {
1245       newValue = Util::DicomString(str, length+1);
1246       gdcmWarningMacro("Warning: bad length: " << length <<
1247                        ",For string :" <<  newValue.c_str()); 
1248       // Since we change the length of string update it length
1249       //entry->SetReadLength(length+1);
1250    }
1251    else
1252    {
1253       newValue = Util::DicomString(str, length);
1254    }
1255    delete[] str;
1256
1257    if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1258    {
1259       if ( Fp->fail() || Fp->eof())
1260       {
1261          gdcmWarningMacro("Unread element value");
1262          valEntry->SetValue(GDCM_UNREAD);
1263          return;
1264       }
1265
1266       if( vr == "UI" )
1267       {
1268          // Because of correspondance with the VR dic
1269          valEntry->SetValue(newValue);
1270       }
1271       else
1272       {
1273          valEntry->SetValue(newValue);
1274       }
1275    }
1276    else
1277    {
1278       gdcmErrorMacro( "Should have a ValEntry, here !");
1279    }
1280 }
1281
1282 /**
1283  * \brief  Find the value Length of the passed Header Entry
1284  * @param  entry Header Entry whose length of the value shall be loaded. 
1285  */
1286 void Document::FindDocEntryLength( DocEntry *entry )
1287    throw ( FormatError )
1288 {
1289    std::string  vr  = entry->GetVR();
1290    uint16_t length16;       
1291    
1292    if ( Filetype == ExplicitVR && !entry->IsImplicitVR() ) 
1293    {
1294       if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" ) 
1295       {
1296          // The following reserved two bytes (see PS 3.5-2003, section
1297          // "7.1.2 Data element structure with explicit vr", p 27) must be
1298          // skipped before proceeding on reading the length on 4 bytes.
1299          Fp->seekg( 2L, std::ios::cur);
1300          uint32_t length32 = ReadInt32();
1301
1302          if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff ) 
1303          {
1304             uint32_t lengthOB;
1305             try 
1306             {
1307                lengthOB = FindDocEntryLengthOBOrOW();
1308             }
1309             catch ( FormatUnexpected )
1310             {
1311                // Computing the length failed (this happens with broken
1312                // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1313                // chance to get the pixels by deciding the element goes
1314                // until the end of the file. Hence we artificially fix the
1315                // the length and proceed.
1316                long currentPosition = Fp->tellg();
1317                Fp->seekg(0L,std::ios::end);
1318
1319                long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1320                Fp->seekg(currentPosition, std::ios::beg);
1321
1322                entry->SetReadLength(lengthUntilEOF);
1323                entry->SetLength(lengthUntilEOF);
1324                return;
1325             }
1326             entry->SetReadLength(lengthOB);
1327             entry->SetLength(lengthOB);
1328             return;
1329          }
1330          FixDocEntryFoundLength(entry, length32); 
1331          return;
1332       }
1333
1334       // Length is encoded on 2 bytes.
1335       length16 = ReadInt16();
1336   
1337       // 0xffff means that we deal with 'No Length' Sequence 
1338       //        or 'No Length' SQItem
1339       if ( length16 == 0xffff) 
1340       {           
1341          length16 = 0;
1342       }
1343       FixDocEntryFoundLength( entry, (uint32_t)length16 );
1344       return;
1345    }
1346    else
1347    {
1348       // Either implicit VR or a non DICOM conformal (see note below) explicit
1349       // VR that ommited the VR of (at least) this element. Farts happen.
1350       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1351       // on Data elements "Implicit and Explicit VR Data Elements shall
1352       // not coexist in a Data Set and Data Sets nested within it".]
1353       // Length is on 4 bytes.
1354
1355      // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1356      // even if Transfer Syntax is 'Implicit VR ...' 
1357       
1358       FixDocEntryFoundLength( entry, ReadInt32() );
1359       return;
1360    }
1361 }
1362
1363 /**
1364  * \brief  Find the Length till the next sequence delimiter
1365  * \warning NOT end user intended method !
1366  * @return 
1367  */
1368 uint32_t Document::FindDocEntryLengthOBOrOW()
1369    throw( FormatUnexpected )
1370 {
1371    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1372    long positionOnEntry = Fp->tellg();
1373    bool foundSequenceDelimiter = false;
1374    uint32_t totalLength = 0;
1375
1376    while ( !foundSequenceDelimiter )
1377    {
1378       uint16_t group;
1379       uint16_t elem;
1380       try
1381       {
1382          group = ReadInt16();
1383          elem  = ReadInt16();   
1384       }
1385       catch ( FormatError )
1386       {
1387          throw FormatError("Unexpected end of file encountered during ",
1388                            "Document::FindDocEntryLengthOBOrOW()");
1389       }
1390       // We have to decount the group and element we just read
1391       totalLength += 4;     
1392       if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1393       {
1394          long filePosition = Fp->tellg();
1395          gdcmWarningMacro( 
1396               "Neither an Item tag nor a Sequence delimiter tag on :" 
1397            << std::hex << group << " , " << elem 
1398            << ") -before- position x(" << filePosition << ")" );
1399   
1400          Fp->seekg(positionOnEntry, std::ios::beg);
1401          throw FormatUnexpected( 
1402                "Neither an Item tag nor a Sequence delimiter tag.");
1403       }
1404       if ( elem == 0xe0dd )
1405       {
1406          foundSequenceDelimiter = true;
1407       }
1408       uint32_t itemLength = ReadInt32();
1409       // We add 4 bytes since we just read the ItemLength with ReadInt32
1410       totalLength += itemLength + 4;
1411       SkipBytes(itemLength);
1412       
1413       if ( foundSequenceDelimiter )
1414       {
1415          break;
1416       }
1417    }
1418    Fp->seekg( positionOnEntry, std::ios::beg);
1419    return totalLength;
1420 }
1421
1422 /**
1423  * \brief     Find the Value Representation of the current Dicom Element.
1424  * @return    Value Representation of the current Entry
1425  */
1426 std::string Document::FindDocEntryVR()
1427 {
1428    if ( Filetype != ExplicitVR )
1429       return GDCM_UNKNOWN;
1430
1431    long positionOnEntry = Fp->tellg();
1432    // Warning: we believe this is explicit VR (Value Representation) because
1433    // we used a heuristic that found "UL" in the first tag. Alas this
1434    // doesn't guarantee that all the tags will be in explicit VR. In some
1435    // cases (see e-film filtered files) one finds implicit VR tags mixed
1436    // within an explicit VR file. Hence we make sure the present tag
1437    // is in explicit VR and try to fix things if it happens not to be
1438    // the case.
1439
1440    char vr[3];
1441    Fp->read (vr, (size_t)2);
1442    vr[2] = 0;
1443
1444    if( !CheckDocEntryVR(vr) )
1445    {
1446       Fp->seekg(positionOnEntry, std::ios::beg);
1447       return GDCM_UNKNOWN;
1448    }
1449    return vr;
1450 }
1451
1452 /**
1453  * \brief     Check the correspondance between the VR of the header entry
1454  *            and the taken VR. If they are different, the header entry is 
1455  *            updated with the new VR.
1456  * @param     vr    Dicom Value Representation
1457  * @return    false if the VR is incorrect of if the VR isn't referenced
1458  *            otherwise, it returns true
1459 */
1460 bool Document::CheckDocEntryVR(VRKey vr)
1461 {
1462    if ( !Global::GetVR()->IsValidVR(vr) )
1463       return false;
1464
1465    return true; 
1466 }
1467
1468 /**
1469  * \brief   Get the transformed value of the header entry. The VR value 
1470  *          is used to define the transformation to operate on the value
1471  * \warning NOT end user intended method !
1472  * @param   entry entry to tranform
1473  * @return  Transformed entry value
1474  */
1475 std::string Document::GetDocEntryValue(DocEntry *entry)
1476 {
1477    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1478    {
1479       std::string val = ((ValEntry *)entry)->GetValue();
1480       std::string vr  = entry->GetVR();
1481       uint32_t length = entry->GetLength();
1482       std::ostringstream s;
1483       int nbInt;
1484
1485       // When short integer(s) are expected, read and convert the following 
1486       // n * 2 bytes properly i.e. as a multivaluated strings
1487       // (each single value is separated fromthe next one by '\'
1488       // as usual for standard multivaluated filels
1489       // Elements with Value Multiplicity > 1
1490       // contain a set of short integers (not a single one) 
1491    
1492       if( vr == "US" || vr == "SS" )
1493       {
1494          uint16_t newInt16;
1495
1496          nbInt = length / 2;
1497          for (int i=0; i < nbInt; i++) 
1498          {
1499             if( i != 0 )
1500             {
1501                s << '\\';
1502             }
1503             newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1504             newInt16 = SwapShort( newInt16 );
1505             s << newInt16;
1506          }
1507       }
1508
1509       // When integer(s) are expected, read and convert the following 
1510       // n * 4 bytes properly i.e. as a multivaluated strings
1511       // (each single value is separated fromthe next one by '\'
1512       // as usual for standard multivaluated filels
1513       // Elements with Value Multiplicity > 1
1514       // contain a set of integers (not a single one) 
1515       else if( vr == "UL" || vr == "SL" )
1516       {
1517          uint32_t newInt32;
1518
1519          nbInt = length / 4;
1520          for (int i=0; i < nbInt; i++) 
1521          {
1522             if( i != 0)
1523             {
1524                s << '\\';
1525             }
1526             newInt32 = ( val[4*i+0] & 0xFF )
1527                     + (( val[4*i+1] & 0xFF ) <<  8 )
1528                     + (( val[4*i+2] & 0xFF ) << 16 )
1529                     + (( val[4*i+3] & 0xFF ) << 24 );
1530             newInt32 = SwapLong( newInt32 );
1531             s << newInt32;
1532          }
1533       }
1534 #ifdef GDCM_NO_ANSI_STRING_STREAM
1535       s << std::ends; // to avoid oddities on Solaris
1536 #endif //GDCM_NO_ANSI_STRING_STREAM
1537       return s.str();
1538    }
1539    return ((ValEntry *)entry)->GetValue();
1540 }
1541
1542 /**
1543  * \brief   Get the reverse transformed value of the header entry. The VR 
1544  *          value is used to define the reverse transformation to operate on
1545  *          the value
1546  * \warning NOT end user intended method !
1547  * @param   entry Entry to reverse transform
1548  * @return  Reverse transformed entry value
1549  */
1550 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1551 {
1552    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1553    {
1554       std::string vr = entry->GetVR();
1555       std::vector<std::string> tokens;
1556       std::ostringstream s;
1557
1558       if ( vr == "US" || vr == "SS" ) 
1559       {
1560          uint16_t newInt16;
1561
1562          tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1563          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1564          for (unsigned int i=0; i<tokens.size(); i++) 
1565          {
1566             newInt16 = atoi(tokens[i].c_str());
1567             s << (  newInt16        & 0xFF ) 
1568               << (( newInt16 >> 8 ) & 0xFF );
1569          }
1570          tokens.clear();
1571       }
1572       if ( vr == "UL" || vr == "SL")
1573       {
1574          uint32_t newInt32;
1575
1576          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1577          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1578          for (unsigned int i=0; i<tokens.size();i++) 
1579          {
1580             newInt32 = atoi(tokens[i].c_str());
1581             s << (char)(  newInt32         & 0xFF ) 
1582               << (char)(( newInt32 >>  8 ) & 0xFF )
1583               << (char)(( newInt32 >> 16 ) & 0xFF )
1584               << (char)(( newInt32 >> 24 ) & 0xFF );
1585          }
1586          tokens.clear();
1587       }
1588
1589 #ifdef GDCM_NO_ANSI_STRING_STREAM
1590       s << std::ends; // to avoid oddities on Solaris
1591 #endif //GDCM_NO_ANSI_STRING_STREAM
1592       return s.str();
1593    }
1594
1595    return ((ValEntry *)entry)->GetValue();
1596 }
1597
1598 /**
1599  * \brief   Skip a given Header Entry 
1600  * \warning NOT end user intended method !
1601  * @param   entry entry to skip
1602  */
1603 void Document::SkipDocEntry(DocEntry *entry) 
1604 {
1605    SkipBytes(entry->GetLength());
1606 }
1607
1608 /**
1609  * \brief   Skips to the beginning of the next Header Entry 
1610  * \warning NOT end user intended method !
1611  * @param   currentDocEntry entry to skip
1612  */
1613 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry) 
1614 {
1615    Fp->seekg((long)(currentDocEntry->GetOffset()),     std::ios::beg);
1616    if (currentDocEntry->GetGroup() != 0xfffe)  // for fffe pb
1617       Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1618 }
1619
1620 /**
1621  * \brief   When the length of an element value is obviously wrong (because
1622  *          the parser went Jabberwocky) one can hope improving things by
1623  *          applying some heuristics.
1624  * @param   entry entry to check
1625  * @param   foundLength first assumption about length    
1626  */
1627 void Document::FixDocEntryFoundLength(DocEntry *entry,
1628                                       uint32_t foundLength)
1629 {
1630    entry->SetReadLength( foundLength ); // will be updated only if a bug is found        
1631    if ( foundLength == 0xffffffff)
1632    {
1633       foundLength = 0;
1634    }
1635    
1636    uint16_t gr   = entry->GetGroup();
1637    uint16_t elem = entry->GetElement(); 
1638      
1639    if ( foundLength % 2)
1640    {
1641       gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength 
1642         <<  " in x(" << std::hex << gr << "," << elem <<")");
1643    }
1644       
1645    //////// Fix for some naughty General Electric images.
1646    // Allthough not recent many such GE corrupted images are still present
1647    // on Creatis hard disks. Hence this fix shall remain when such images
1648    // are no longer in use (we are talking a few years, here)...
1649    // Note: XMedCom probably uses such a trick since it is able to read
1650    //       those pesky GE images ...
1651    if ( foundLength == 13)
1652    {
1653       // Only happens for this length !
1654       if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1655       {
1656          foundLength = 10;
1657          entry->SetReadLength(10); // a bug is to be fixed !?
1658       }
1659    }
1660
1661    //////// Fix for some brain-dead 'Leonardo' Siemens images.
1662    // Occurence of such images is quite low (unless one leaves close to a
1663    // 'Leonardo' source. Hence, one might consider commenting out the
1664    // following fix on efficiency reasons.
1665    else if ( gr   == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1666    {
1667       foundLength = 4;
1668       entry->SetReadLength(4); // a bug is to be fixed !?
1669    } 
1670  
1671    else if ( entry->GetVR() == "SQ" )
1672    {
1673       foundLength = 0;      // ReadLength is unchanged 
1674    } 
1675     
1676    //////// We encountered a 'delimiter' element i.e. a tag of the form 
1677    // "fffe|xxxx" which is just a marker. Delimiters length should not be
1678    // taken into account.
1679    else if( gr == 0xfffe )
1680    {    
1681      // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1682      // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1683      // causes extra troubles...
1684      if( entry->GetElement() != 0x0000 )
1685      {
1686         foundLength = 0;
1687      }
1688    }            
1689    entry->SetLength(foundLength);
1690 }
1691
1692 /**
1693  * \brief   Apply some heuristics to predict whether the considered 
1694  *          element value contains/represents an integer or not.
1695  * @param   entry The element value on which to apply the predicate.
1696  * @return  The result of the heuristical predicate.
1697  */
1698 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1699 {
1700    uint16_t elem         = entry->GetElement();
1701    uint16_t group        = entry->GetGroup();
1702    const std::string &vr = entry->GetVR();
1703    uint32_t length       = entry->GetLength();
1704
1705    // When we have some semantics on the element we just read, and if we
1706    // a priori know we are dealing with an integer, then we shall be
1707    // able to swap it's element value properly.
1708    if ( elem == 0 )  // This is the group length of the group
1709    {  
1710       if ( length == 4 )
1711       {
1712          return true;
1713       }
1714       else 
1715       {
1716          // Allthough this should never happen, still some images have a
1717          // corrupted group length [e.g. have a glance at offset x(8336) of
1718          // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1719          // Since for dicom compliant and well behaved headers, the present
1720          // test is useless (and might even look a bit paranoid), when we
1721          // encounter such an ill-formed image, we simply display a warning
1722          // message and proceed on parsing (while crossing fingers).
1723          long filePosition = Fp->tellg();
1724          gdcmWarningMacro( "Erroneous Group Length element length  on : (" 
1725            << std::hex << group << " , " << elem
1726            << ") -before- position x(" << filePosition << ")"
1727            << "lgt : " << length );
1728       }
1729    }
1730
1731    if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1732    {
1733       return true;
1734    }   
1735    return false;
1736 }
1737
1738 /**
1739  * \brief   Discover what the swap code is (among little endian, big endian,
1740  *          bad little endian, bad big endian).
1741  *          sw is set
1742  * @return false when we are absolutely sure 
1743  *               it's neither ACR-NEMA nor DICOM
1744  *         true  when we hope ours assuptions are OK
1745  */
1746 bool Document::CheckSwap()
1747 {
1748    // The only guaranted way of finding the swap code is to find a
1749    // group tag since we know it's length has to be of four bytes i.e.
1750    // 0x00000004. Finding the swap code in then straigthforward. Trouble
1751    // occurs when we can't find such group...
1752    
1753    uint32_t  s32;
1754    uint16_t  s16;
1755        
1756    char deb[256];
1757     
1758    // First, compare HostByteOrder and NetworkByteOrder in order to
1759    // determine if we shall need to swap bytes (i.e. the Endian type).
1760    bool net2host = Util::IsCurrentProcessorBigEndian();
1761          
1762    // The easiest case is the one of a 'true' DICOM header, we just have
1763    // to look for the string "DICM" inside the file preamble.
1764    Fp->read(deb, 256);
1765    
1766    char *entCur = deb + 128;
1767    if( memcmp(entCur, "DICM", (size_t)4) == 0 )
1768    {
1769       gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1770       
1771       // Group 0002 should always be VR, and the first element 0000
1772       // Let's be carefull (so many wrong headers ...)
1773       // and determine the value representation (VR) : 
1774       // Let's skip to the first element (0002,0000) and check there if we find
1775       // "UL"  - or "OB" if the 1st one is (0002,0001) -,
1776       // in which case we (almost) know it is explicit VR.
1777       // WARNING: if it happens to be implicit VR then what we will read
1778       // is the length of the group. If this ascii representation of this
1779       // length happens to be "UL" then we shall believe it is explicit VR.
1780       // We need to skip :
1781       // * the 128 bytes of File Preamble (often padded with zeroes),
1782       // * the 4 bytes of "DICM" string,
1783       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1784       // i.e. a total of  136 bytes.
1785       entCur = deb + 136;
1786      
1787       // group 0x0002 *is always* Explicit VR Sometimes ,
1788       // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1789       // *Implicit* VR  (see former 'gdcmData/icone.dcm')
1790       
1791       if( memcmp(entCur, "UL", (size_t)2) == 0 ||
1792           memcmp(entCur, "OB", (size_t)2) == 0 ||
1793           memcmp(entCur, "UI", (size_t)2) == 0 ||
1794           memcmp(entCur, "CS", (size_t)2) == 0 )  // CS, to remove later
1795                                                   // when Write DCM *adds*
1796       // FIXME
1797       // Use Document::dicom_vr to test all the possibilities
1798       // instead of just checking for UL, OB and UI !? group 0000 
1799       {
1800          Filetype = ExplicitVR;
1801          gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1802       } 
1803       else 
1804       {
1805          Filetype = ImplicitVR;
1806          gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1807                         << "Looks like a bugged Header!");
1808       }
1809       
1810       if ( net2host )
1811       {
1812          SwapCode = 4321;
1813          gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
1814       }
1815       else 
1816       {
1817          SwapCode = 1234;
1818          gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
1819       }
1820       
1821       // Position the file position indicator at first tag 
1822       // (i.e. after the file preamble and the "DICM" string).
1823       Fp->seekg(0, std::ios::beg);
1824       Fp->seekg ( 132L, std::ios::beg);
1825       return true;
1826    } // ------------------------------- End of DicomV3 ----------------
1827
1828    // Alas, this is not a DicomV3 file and whatever happens there is no file
1829    // preamble. We can reset the file position indicator to where the data
1830    // is (i.e. the beginning of the file).
1831
1832    gdcmWarningMacro( "Not a DICOM Version3 file");
1833
1834    Fp->seekg(0, std::ios::beg);
1835
1836    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1837    // By clean we mean that the length of the first group is written down.
1838    // If this is the case and since the length of the first group HAS to be
1839    // four (bytes), then determining the proper swap code is straightforward.
1840
1841    entCur = deb + 4;
1842    // We assume the array of char we are considering contains the binary
1843    // representation of a 32 bits integer. Hence the following dirty
1844    // trick :
1845    s32 = *((uint32_t *)(entCur));
1846    switch( s32 )
1847    {
1848       case 0x00040000 :
1849          SwapCode = 3412;
1850          Filetype = ACR;
1851          return true;
1852       case 0x04000000 :
1853          SwapCode = 4321;
1854          Filetype = ACR;
1855          return true;
1856       case 0x00000400 :
1857          SwapCode = 2143;
1858          Filetype = ACR;
1859          return true;
1860       case 0x00000004 :
1861          SwapCode = 1234;
1862          Filetype = ACR;
1863          return true;
1864       default :
1865          // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1866          // It is time for despaired wild guesses. 
1867          // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1868          //  i.e. the 'group length' element is not present :     
1869          
1870          //  check the supposed-to-be 'group number'
1871          //  in ( 0x0001 .. 0x0008 )
1872          //  to determine ' SwapCode' value .
1873          //  Only 0 or 4321 will be possible 
1874          //  (no oportunity to check for the formerly well known
1875          //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
1876          //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-) 
1877          //  the file IS NOT ACR-NEMA nor DICOM V3
1878          //  Find a trick to tell it the caller...
1879       
1880          s16 = *((uint16_t *)(deb));
1881       
1882          switch ( s16 )
1883          {
1884             case 0x0001 :
1885             case 0x0002 :
1886             case 0x0003 :
1887             case 0x0004 :
1888             case 0x0005 :
1889             case 0x0006 :
1890             case 0x0007 :
1891             case 0x0008 :
1892                SwapCode = 1234;
1893                Filetype = ACR;
1894                return true;
1895             case 0x0100 :
1896             case 0x0200 :
1897             case 0x0300 :
1898             case 0x0400 :
1899             case 0x0500 :
1900             case 0x0600 :
1901             case 0x0700 :
1902             case 0x0800 :
1903                SwapCode = 4321;
1904                Filetype = ACR;
1905                return true;
1906             default :
1907                gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1908                Filetype = Unknown;
1909                return false;
1910          }
1911    }
1912 }
1913
1914 /**
1915  * \brief Change the Byte Swap code. 
1916  */
1917 void Document::SwitchByteSwapCode() 
1918 {
1919    gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode);
1920    if ( SwapCode == 1234 ) 
1921    {
1922       SwapCode = 4321;
1923    }
1924    else if ( SwapCode == 4321 ) 
1925    {
1926       SwapCode = 1234;
1927    }
1928    else if ( SwapCode == 3412 ) 
1929    {
1930       SwapCode = 2143;
1931    }
1932    else if ( SwapCode == 2143 )
1933    {
1934       SwapCode = 3412;
1935    }
1936 }
1937
1938 /**
1939  * \brief  during parsing, Header Elements too long are not loaded in memory 
1940  * @param newSize new size
1941  */
1942 void Document::SetMaxSizeLoadEntry(long newSize) 
1943 {
1944    if ( newSize < 0 )
1945    {
1946       return;
1947    }
1948    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1949    {
1950       MaxSizeLoadEntry = 0xffffffff;
1951       return;
1952    }
1953    MaxSizeLoadEntry = newSize;
1954 }
1955
1956 /**
1957  * \brief   Read the next tag but WITHOUT loading it's value
1958  *          (read the 'Group Number', the 'Element Number',
1959  *          gets the Dict Entry
1960  *          gets the VR, gets the length, gets the offset value)
1961  * @return  On succes the newly created DocEntry, NULL on failure.      
1962  */
1963 DocEntry *Document::ReadNextDocEntry()
1964 {
1965    uint16_t group;
1966    uint16_t elem;
1967
1968    try
1969    {
1970       group = ReadInt16();
1971       elem  = ReadInt16();
1972    }
1973    catch ( FormatError e )
1974    {
1975       // We reached the EOF (or an error occured) therefore 
1976       // header parsing has to be considered as finished.
1977       return 0;
1978    }
1979
1980    // Sometimes file contains groups of tags with reversed endianess.
1981    HandleBrokenEndian(group, elem);
1982
1983    // In 'true DICOM' files Group 0002 is always little endian
1984    if ( HasDCMPreamble )
1985       HandleOutOfGroup0002(group, elem);
1986  
1987    std::string vr = FindDocEntryVR();
1988    std::string realVR = vr;
1989
1990    if( vr == GDCM_UNKNOWN)
1991    {
1992       if ( elem == 0x0000 ) // Group Length
1993          realVR = "UL";     // must be UL
1994       else
1995       {
1996          DictEntry *dictEntry = GetDictEntry(group,elem);
1997          if( dictEntry )
1998             realVR = dictEntry->GetVR();
1999       }
2000    }
2001
2002    DocEntry *newEntry;
2003    if( Global::GetVR()->IsVROfSequence(realVR) )
2004       newEntry = NewSeqEntry(group, elem);
2005    else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2006       newEntry = NewValEntry(group, elem,vr);
2007    else
2008       newEntry = NewBinEntry(group, elem,vr);
2009
2010    if( vr == GDCM_UNKNOWN )
2011    {
2012       if( Filetype == ExplicitVR )
2013       {
2014          // We thought this was explicit VR, but we end up with an
2015          // implicit VR tag. Let's backtrack.
2016          if ( newEntry->GetGroup() != 0xfffe )
2017          { 
2018             std::string msg;
2019             msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n", 
2020                           newEntry->GetGroup(), newEntry->GetElement());
2021             gdcmWarningMacro( msg.c_str() );
2022           }
2023       }
2024       newEntry->SetImplicitVR();
2025    }
2026
2027    try
2028    {
2029       FindDocEntryLength(newEntry);
2030    }
2031    catch ( FormatError e )
2032    {
2033       // Call it quits
2034       delete newEntry;
2035       return 0;
2036    }
2037
2038    newEntry->SetOffset(Fp->tellg());  
2039
2040    return newEntry;
2041 }
2042
2043 /**
2044  * \brief   Handle broken private tag from Philips NTSCAN
2045  *          where the endianess is being switch to BigEndian for no
2046  *          apparent reason
2047  * @return  no return
2048  */
2049 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2050 {
2051    // Endian reversion. Some files contain groups of tags with reversed endianess.
2052    static int reversedEndian = 0;
2053    // try to fix endian switching in the middle of headers
2054    if ((group == 0xfeff) && (elem == 0x00e0))
2055    {
2056      // start endian swap mark for group found
2057      reversedEndian++;
2058      SwitchByteSwapCode();
2059      // fix the tag
2060      group = 0xfffe;
2061      elem  = 0xe000;
2062    } 
2063    else if (group == 0xfffe && elem == 0xe00d && reversedEndian) 
2064    {
2065      // end of reversed endian group
2066      reversedEndian--;
2067      SwitchByteSwapCode();
2068    }
2069 }
2070
2071 /**
2072  * \brief   Group 0002 is always coded Little Endian
2073  *          whatever Transfer Syntax is
2074  * @return  no return
2075  */
2076 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2077 {
2078    // Endian reversion. Some files contain groups of tags with reversed endianess.
2079    if ( !Group0002Parsed && group != 0x0002)
2080    {
2081       Group0002Parsed = true;
2082       // we just came out of group 0002
2083       // if Transfer syntax is Big Endian we have to change CheckSwap
2084
2085       std::string ts = GetTransferSyntax();
2086       if ( !Global::GetTS()->IsTransferSyntax(ts) )
2087       {
2088          gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2089          return;
2090       }
2091
2092       // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..." 
2093
2094       if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2095          {
2096             Filetype = ImplicitVR;
2097          }
2098        
2099       // FIXME Strangely, this works with 
2100       //'Implicit VR Transfer Syntax (GE Private)
2101       if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2102       {
2103          gdcmWarningMacro("Transfer Syntax Name = [" 
2104                         << GetTransferSyntaxName() << "]" );
2105          SwitchByteSwapCode();
2106          group = SwapShort(group);
2107          elem  = SwapShort(elem);
2108       }
2109    }
2110 }
2111
2112 //-----------------------------------------------------------------------------
2113 // Print
2114
2115 //-----------------------------------------------------------------------------
2116 } // end namespace gdcm