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