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