]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
Comments
[gdcm.git] / src / gdcmDocument.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDocument.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/04/05 10:20:53 $
7   Version:   $Revision: 1.234 $
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 << " Address:" << (long)entry->GetOffset();
1112          s << " Length:"  << entry->GetLength();
1113          s << " x(" << std::hex << entry->GetLength() << ")";
1114          binEntryPtr->SetValue(s.str());
1115       }
1116       // Be carefull : a BinEntry IS_A ValEntry ... 
1117       else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1118       {
1119         // s << "gdcm::NotLoaded. (ValEntry)";
1120          s << GDCM_NOTLOADED;  
1121          s << " Address:" << (long)entry->GetOffset();
1122          s << " Length:"  << entry->GetLength();
1123          s << " x(" << std::hex << entry->GetLength() << ")";
1124          valEntryPtr->SetValue(s.str());
1125       }
1126       else
1127       {
1128          // fusible
1129          gdcmErrorMacro( "MaxSizeLoadEntry exceeded, neither a BinEntry "
1130                       << "nor a ValEntry ?! Should never print that !" );
1131       }
1132
1133       // to be sure we are at the end of the value ...
1134       Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1135                 std::ios::beg);
1136       return;
1137    }
1138
1139    // When we find a BinEntry not very much can be done :
1140    if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1141    {
1142       s << GDCM_BINLOADED;
1143       binEntryPtr->SetValue(s.str());
1144       LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1145       return;
1146    }
1147
1148    if ( IsDocEntryAnInteger(entry) )
1149    {   
1150       uint32_t NewInt;
1151       int nbInt;
1152       // When short integer(s) are expected, read and convert the following 
1153       // n *two characters properly i.e. consider them as short integers as
1154       // opposed to strings.
1155       // Elements with Value Multiplicity > 1
1156       // contain a set of integers (not a single one)       
1157       if (vr == "US" || vr == "SS")
1158       {
1159          nbInt = length / 2;
1160          NewInt = ReadInt16();
1161          s << NewInt;
1162          if (nbInt > 1)
1163          {
1164             for (int i=1; i < nbInt; i++)
1165             {
1166                s << '\\';
1167                NewInt = ReadInt16();
1168                s << NewInt;
1169             }
1170          }
1171       }
1172       // See above comment on multiple integers (mutatis mutandis).
1173       else if (vr == "UL" || vr == "SL")
1174       {
1175          nbInt = length / 4;
1176          NewInt = ReadInt32();
1177          s << NewInt;
1178          if (nbInt > 1)
1179          {
1180             for (int i=1; i < nbInt; i++)
1181             {
1182                s << '\\';
1183                NewInt = ReadInt32();
1184                s << NewInt;
1185             }
1186          }
1187       }
1188 #ifdef GDCM_NO_ANSI_STRING_STREAM
1189       s << std::ends; // to avoid oddities on Solaris
1190 #endif //GDCM_NO_ANSI_STRING_STREAM
1191
1192       ((ValEntry *)entry)->SetValue(s.str());
1193       return;
1194    }
1195    
1196   // FIXME: We need an additional byte for storing \0 that is not on disk
1197    char *str = new char[length+1];
1198    Fp->read(str, (size_t)length);
1199    str[length] = '\0'; //this is only useful when length is odd
1200    // Special DicomString call to properly handle \0 and even length
1201    std::string newValue;
1202    if( length % 2 )
1203    {
1204       newValue = Util::DicomString(str, length+1);
1205       gdcmWarningMacro("Warning: bad length: " << length <<
1206                        ",For string :" <<  newValue.c_str()); 
1207       // Since we change the length of string update it length
1208       //entry->SetReadLength(length+1);
1209    }
1210    else
1211    {
1212       newValue = Util::DicomString(str, length);
1213    }
1214    delete[] str;
1215
1216    if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1217    {
1218       if ( Fp->fail() || Fp->eof())
1219       {
1220          gdcmWarningMacro("Unread element value");
1221          valEntry->SetValue(GDCM_UNREAD);
1222          return;
1223       }
1224
1225       if( vr == "UI" )
1226       {
1227          // Because of correspondance with the VR dic
1228          valEntry->SetValue(newValue);
1229       }
1230       else
1231       {
1232          valEntry->SetValue(newValue);
1233       }
1234    }
1235    else
1236    {
1237       gdcmErrorMacro( "Should have a ValEntry, here !");
1238    }
1239 }
1240
1241 /**
1242  * \brief  Find the value Length of the passed Header Entry
1243  * @param  entry Header Entry whose length of the value shall be loaded. 
1244  */
1245 void Document::FindDocEntryLength( DocEntry *entry )
1246    throw ( FormatError )
1247 {
1248    std::string  vr  = entry->GetVR();
1249    uint16_t length16;       
1250    
1251    if ( Filetype == ExplicitVR && !entry->IsImplicitVR() ) 
1252    {
1253       if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" ) 
1254       {
1255          // The following reserved two bytes (see PS 3.5-2003, section
1256          // "7.1.2 Data element structure with explicit vr", p 27) must be
1257          // skipped before proceeding on reading the length on 4 bytes.
1258          Fp->seekg( 2L, std::ios::cur);
1259          uint32_t length32 = ReadInt32();
1260
1261          if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff ) 
1262          {
1263             uint32_t lengthOB;
1264             try 
1265             {
1266                lengthOB = FindDocEntryLengthOBOrOW();
1267             }
1268             catch ( FormatUnexpected )
1269             {
1270                // Computing the length failed (this happens with broken
1271                // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1272                // chance to get the pixels by deciding the element goes
1273                // until the end of the file. Hence we artificially fix the
1274                // the length and proceed.
1275                long currentPosition = Fp->tellg();
1276                Fp->seekg(0L,std::ios::end);
1277
1278                long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1279                Fp->seekg(currentPosition, std::ios::beg);
1280
1281                entry->SetReadLength(lengthUntilEOF);
1282                entry->SetLength(lengthUntilEOF);
1283                return;
1284             }
1285             entry->SetReadLength(lengthOB);
1286             entry->SetLength(lengthOB);
1287             return;
1288          }
1289          FixDocEntryFoundLength(entry, length32); 
1290          return;
1291       }
1292
1293       // Length is encoded on 2 bytes.
1294       length16 = ReadInt16();
1295   
1296       // 0xffff means that we deal with 'No Length' Sequence 
1297       //        or 'No Length' SQItem
1298       if ( length16 == 0xffff) 
1299       {           
1300          length16 = 0;
1301       }
1302       FixDocEntryFoundLength( entry, (uint32_t)length16 );
1303       return;
1304    }
1305    else
1306    {
1307       // Either implicit VR or a non DICOM conformal (see note below) explicit
1308       // VR that ommited the VR of (at least) this element. Farts happen.
1309       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1310       // on Data elements "Implicit and Explicit VR Data Elements shall
1311       // not coexist in a Data Set and Data Sets nested within it".]
1312       // Length is on 4 bytes.
1313
1314      // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1315      // even if Transfer Syntax is 'Implicit VR ...' 
1316       
1317       FixDocEntryFoundLength( entry, ReadInt32() );
1318       return;
1319    }
1320 }
1321
1322 /**
1323  * \brief  Find the Length till the next sequence delimiter
1324  * \warning NOT end user intended method !
1325  * @return 
1326  */
1327 uint32_t Document::FindDocEntryLengthOBOrOW()
1328    throw( FormatUnexpected )
1329 {
1330    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1331    long positionOnEntry = Fp->tellg();
1332    bool foundSequenceDelimiter = false;
1333    uint32_t totalLength = 0;
1334
1335    while ( !foundSequenceDelimiter )
1336    {
1337       uint16_t group;
1338       uint16_t elem;
1339       try
1340       {
1341          group = ReadInt16();
1342          elem  = ReadInt16();   
1343       }
1344       catch ( FormatError )
1345       {
1346          throw FormatError("Unexpected end of file encountered during ",
1347                            "Document::FindDocEntryLengthOBOrOW()");
1348       }
1349       // We have to decount the group and element we just read
1350       totalLength += 4;     
1351       if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1352       {
1353          long filePosition = Fp->tellg();
1354          gdcmWarningMacro( 
1355               "Neither an Item tag nor a Sequence delimiter tag on :" 
1356            << std::hex << group << " , " << elem 
1357            << ") -before- position x(" << filePosition << ")" );
1358   
1359          Fp->seekg(positionOnEntry, std::ios::beg);
1360          throw FormatUnexpected( 
1361                "Neither an Item tag nor a Sequence delimiter tag.");
1362       }
1363       if ( elem == 0xe0dd )
1364       {
1365          foundSequenceDelimiter = true;
1366       }
1367       uint32_t itemLength = ReadInt32();
1368       // We add 4 bytes since we just read the ItemLength with ReadInt32
1369       totalLength += itemLength + 4;
1370       SkipBytes(itemLength);
1371       
1372       if ( foundSequenceDelimiter )
1373       {
1374          break;
1375       }
1376    }
1377    Fp->seekg( positionOnEntry, std::ios::beg);
1378    return totalLength;
1379 }
1380
1381 /**
1382  * \brief     Find the Value Representation of the current Dicom Element.
1383  * @return    Value Representation of the current Entry
1384  */
1385 std::string Document::FindDocEntryVR()
1386 {
1387    if ( Filetype != ExplicitVR )
1388       return GDCM_UNKNOWN;
1389
1390    long positionOnEntry = Fp->tellg();
1391    // Warning: we believe this is explicit VR (Value Representation) because
1392    // we used a heuristic that found "UL" in the first tag. Alas this
1393    // doesn't guarantee that all the tags will be in explicit VR. In some
1394    // cases (see e-film filtered files) one finds implicit VR tags mixed
1395    // within an explicit VR file. Hence we make sure the present tag
1396    // is in explicit VR and try to fix things if it happens not to be
1397    // the case.
1398
1399    char vr[3];
1400    Fp->read (vr, (size_t)2);
1401    vr[2] = 0;
1402
1403    if( !CheckDocEntryVR(vr) )
1404    {
1405       Fp->seekg(positionOnEntry, std::ios::beg);
1406       return GDCM_UNKNOWN;
1407    }
1408    return vr;
1409 }
1410
1411 /**
1412  * \brief     Check the correspondance between the VR of the header entry
1413  *            and the taken VR. If they are different, the header entry is 
1414  *            updated with the new VR.
1415  * @param     vr    Dicom Value Representation
1416  * @return    false if the VR is incorrect of if the VR isn't referenced
1417  *            otherwise, it returns true
1418 */
1419 bool Document::CheckDocEntryVR(VRKey vr)
1420 {
1421    if ( !Global::GetVR()->IsValidVR(vr) )
1422       return false;
1423
1424    return true; 
1425 }
1426
1427 /**
1428  * \brief   Get the transformed value of the header entry. The VR value 
1429  *          is used to define the transformation to operate on the value
1430  * \warning NOT end user intended method !
1431  * @param   entry entry to tranform
1432  * @return  Transformed entry value
1433  */
1434 std::string Document::GetDocEntryValue(DocEntry *entry)
1435 {
1436    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1437    {
1438       std::string val = ((ValEntry *)entry)->GetValue();
1439       std::string vr  = entry->GetVR();
1440       uint32_t length = entry->GetLength();
1441       std::ostringstream s;
1442       int nbInt;
1443
1444       // When short integer(s) are expected, read and convert the following 
1445       // n * 2 bytes properly i.e. as a multivaluated strings
1446       // (each single value is separated fromthe next one by '\'
1447       // as usual for standard multivaluated filels
1448       // Elements with Value Multiplicity > 1
1449       // contain a set of short integers (not a single one) 
1450    
1451       if( vr == "US" || vr == "SS" )
1452       {
1453          uint16_t newInt16;
1454
1455          nbInt = length / 2;
1456          for (int i=0; i < nbInt; i++) 
1457          {
1458             if( i != 0 )
1459             {
1460                s << '\\';
1461             }
1462             newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1463             newInt16 = SwapShort( newInt16 );
1464             s << newInt16;
1465          }
1466       }
1467
1468       // When integer(s) are expected, read and convert the following 
1469       // n * 4 bytes properly i.e. as a multivaluated strings
1470       // (each single value is separated fromthe next one by '\'
1471       // as usual for standard multivaluated filels
1472       // Elements with Value Multiplicity > 1
1473       // contain a set of integers (not a single one) 
1474       else if( vr == "UL" || vr == "SL" )
1475       {
1476          uint32_t newInt32;
1477
1478          nbInt = length / 4;
1479          for (int i=0; i < nbInt; i++) 
1480          {
1481             if( i != 0)
1482             {
1483                s << '\\';
1484             }
1485             newInt32 = ( val[4*i+0] & 0xFF )
1486                     + (( val[4*i+1] & 0xFF ) <<  8 )
1487                     + (( val[4*i+2] & 0xFF ) << 16 )
1488                     + (( val[4*i+3] & 0xFF ) << 24 );
1489             newInt32 = SwapLong( newInt32 );
1490             s << newInt32;
1491          }
1492       }
1493 #ifdef GDCM_NO_ANSI_STRING_STREAM
1494       s << std::ends; // to avoid oddities on Solaris
1495 #endif //GDCM_NO_ANSI_STRING_STREAM
1496       return s.str();
1497    }
1498    return ((ValEntry *)entry)->GetValue();
1499 }
1500
1501 /**
1502  * \brief   Get the reverse transformed value of the header entry. The VR 
1503  *          value is used to define the reverse transformation to operate on
1504  *          the value
1505  * \warning NOT end user intended method !
1506  * @param   entry Entry to reverse transform
1507  * @return  Reverse transformed entry value
1508  */
1509 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1510 {
1511    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1512    {
1513       std::string vr = entry->GetVR();
1514       std::vector<std::string> tokens;
1515       std::ostringstream s;
1516
1517       if ( vr == "US" || vr == "SS" ) 
1518       {
1519          uint16_t newInt16;
1520
1521          tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1522          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1523          for (unsigned int i=0; i<tokens.size(); i++) 
1524          {
1525             newInt16 = atoi(tokens[i].c_str());
1526             s << (  newInt16        & 0xFF ) 
1527               << (( newInt16 >> 8 ) & 0xFF );
1528          }
1529          tokens.clear();
1530       }
1531       if ( vr == "UL" || vr == "SL")
1532       {
1533          uint32_t newInt32;
1534
1535          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1536          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1537          for (unsigned int i=0; i<tokens.size();i++) 
1538          {
1539             newInt32 = atoi(tokens[i].c_str());
1540             s << (char)(  newInt32         & 0xFF ) 
1541               << (char)(( newInt32 >>  8 ) & 0xFF )
1542               << (char)(( newInt32 >> 16 ) & 0xFF )
1543               << (char)(( newInt32 >> 24 ) & 0xFF );
1544          }
1545          tokens.clear();
1546       }
1547
1548 #ifdef GDCM_NO_ANSI_STRING_STREAM
1549       s << std::ends; // to avoid oddities on Solaris
1550 #endif //GDCM_NO_ANSI_STRING_STREAM
1551       return s.str();
1552    }
1553
1554    return ((ValEntry *)entry)->GetValue();
1555 }
1556
1557 /**
1558  * \brief   Skip a given Header Entry 
1559  * \warning NOT end user intended method !
1560  * @param   entry entry to skip
1561  */
1562 void Document::SkipDocEntry(DocEntry *entry) 
1563 {
1564    SkipBytes(entry->GetLength());
1565 }
1566
1567 /**
1568  * \brief   Skips to the beginning of the next Header Entry 
1569  * \warning NOT end user intended method !
1570  * @param   currentDocEntry entry to skip
1571  */
1572 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry) 
1573 {
1574    Fp->seekg((long)(currentDocEntry->GetOffset()),     std::ios::beg);
1575    if (currentDocEntry->GetGroup() != 0xfffe)  // for fffe pb
1576       Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1577 }
1578
1579 /**
1580  * \brief   When the length of an element value is obviously wrong (because
1581  *          the parser went Jabberwocky) one can hope improving things by
1582  *          applying some heuristics.
1583  * @param   entry entry to check
1584  * @param   foundLength first assumption about length    
1585  */
1586 void Document::FixDocEntryFoundLength(DocEntry *entry,
1587                                       uint32_t foundLength)
1588 {
1589    entry->SetReadLength( foundLength ); // will be updated only if a bug is found        
1590    if ( foundLength == 0xffffffff)
1591    {
1592       foundLength = 0;
1593    }
1594    
1595    uint16_t gr   = entry->GetGroup();
1596    uint16_t elem = entry->GetElement(); 
1597      
1598    if ( foundLength % 2)
1599    {
1600       gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength 
1601         <<  " in x(" << std::hex << gr << "," << elem <<")");
1602    }
1603       
1604    //////// Fix for some naughty General Electric images.
1605    // Allthough not recent many such GE corrupted images are still present
1606    // on Creatis hard disks. Hence this fix shall remain when such images
1607    // are no longer in use (we are talking a few years, here)...
1608    // Note: XMedCom probably uses such a trick since it is able to read
1609    //       those pesky GE images ...
1610    if ( foundLength == 13)
1611    {
1612       // Only happens for this length !
1613       if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1614       {
1615          foundLength = 10;
1616          entry->SetReadLength(10); // a bug is to be fixed !?
1617       }
1618    }
1619
1620    //////// Fix for some brain-dead 'Leonardo' Siemens images.
1621    // Occurence of such images is quite low (unless one leaves close to a
1622    // 'Leonardo' source. Hence, one might consider commenting out the
1623    // following fix on efficiency reasons.
1624    else if ( gr   == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1625    {
1626       foundLength = 4;
1627       entry->SetReadLength(4); // a bug is to be fixed !?
1628    } 
1629  
1630    else if ( entry->GetVR() == "SQ" )
1631    {
1632       foundLength = 0;      // ReadLength is unchanged 
1633    } 
1634     
1635    //////// We encountered a 'delimiter' element i.e. a tag of the form 
1636    // "fffe|xxxx" which is just a marker. Delimiters length should not be
1637    // taken into account.
1638    else if( gr == 0xfffe )
1639    {    
1640      // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1641      // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1642      // causes extra troubles...
1643      if( entry->GetElement() != 0x0000 )
1644      {
1645         foundLength = 0;
1646      }
1647    }            
1648    entry->SetLength(foundLength);
1649 }
1650
1651 /**
1652  * \brief   Apply some heuristics to predict whether the considered 
1653  *          element value contains/represents an integer or not.
1654  * @param   entry The element value on which to apply the predicate.
1655  * @return  The result of the heuristical predicate.
1656  */
1657 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1658 {
1659    uint16_t elem         = entry->GetElement();
1660    uint16_t group        = entry->GetGroup();
1661    const std::string &vr = entry->GetVR();
1662    uint32_t length       = entry->GetLength();
1663
1664    // When we have some semantics on the element we just read, and if we
1665    // a priori know we are dealing with an integer, then we shall be
1666    // able to swap it's element value properly.
1667    if ( elem == 0 )  // This is the group length of the group
1668    {  
1669       if ( length == 4 )
1670       {
1671          return true;
1672       }
1673       else 
1674       {
1675          // Allthough this should never happen, still some images have a
1676          // corrupted group length [e.g. have a glance at offset x(8336) of
1677          // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1678          // Since for dicom compliant and well behaved headers, the present
1679          // test is useless (and might even look a bit paranoid), when we
1680          // encounter such an ill-formed image, we simply display a warning
1681          // message and proceed on parsing (while crossing fingers).
1682          long filePosition = Fp->tellg();
1683          gdcmWarningMacro( "Erroneous Group Length element length  on : (" 
1684            << std::hex << group << " , " << elem
1685            << ") -before- position x(" << filePosition << ")"
1686            << "lgt : " << length );
1687       }
1688    }
1689
1690    if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1691    {
1692       return true;
1693    }   
1694    return false;
1695 }
1696
1697 /**
1698  * \brief   Discover what the swap code is (among little endian, big endian,
1699  *          bad little endian, bad big endian).
1700  *          sw is set
1701  * @return false when we are absolutely sure 
1702  *               it's neither ACR-NEMA nor DICOM
1703  *         true  when we hope ours assuptions are OK
1704  */
1705 bool Document::CheckSwap()
1706 {
1707    // The only guaranted way of finding the swap code is to find a
1708    // group tag since we know it's length has to be of four bytes i.e.
1709    // 0x00000004. Finding the swap code in then straigthforward. Trouble
1710    // occurs when we can't find such group...
1711    
1712    uint32_t  s32;
1713    uint16_t  s16;
1714        
1715    char deb[256];
1716     
1717    // First, compare HostByteOrder and NetworkByteOrder in order to
1718    // determine if we shall need to swap bytes (i.e. the Endian type).
1719    bool net2host = Util::IsCurrentProcessorBigEndian();
1720          
1721    // The easiest case is the one of a 'true' DICOM header, we just have
1722    // to look for the string "DICM" inside the file preamble.
1723    Fp->read(deb, 256);
1724    
1725    char *entCur = deb + 128;
1726    if( memcmp(entCur, "DICM", (size_t)4) == 0 )
1727    {
1728       gdcmWarningMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1729       
1730       // Group 0002 should always be VR, and the first element 0000
1731       // Let's be carefull (so many wrong headers ...)
1732       // and determine the value representation (VR) : 
1733       // Let's skip to the first element (0002,0000) and check there if we find
1734       // "UL"  - or "OB" if the 1st one is (0002,0001) -,
1735       // in which case we (almost) know it is explicit VR.
1736       // WARNING: if it happens to be implicit VR then what we will read
1737       // is the length of the group. If this ascii representation of this
1738       // length happens to be "UL" then we shall believe it is explicit VR.
1739       // We need to skip :
1740       // * the 128 bytes of File Preamble (often padded with zeroes),
1741       // * the 4 bytes of "DICM" string,
1742       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1743       // i.e. a total of  136 bytes.
1744       entCur = deb + 136;
1745      
1746       // group 0x0002 *is always* Explicit VR Sometimes ,
1747       // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1748       // *Implicit* VR  (see former 'gdcmData/icone.dcm')
1749       
1750       if( memcmp(entCur, "UL", (size_t)2) == 0 ||
1751           memcmp(entCur, "OB", (size_t)2) == 0 ||
1752           memcmp(entCur, "UI", (size_t)2) == 0 ||
1753           memcmp(entCur, "CS", (size_t)2) == 0 )  // CS, to remove later
1754                                                   // when Write DCM *adds*
1755       // FIXME
1756       // Use Document::dicom_vr to test all the possibilities
1757       // instead of just checking for UL, OB and UI !? group 0000 
1758       {
1759          Filetype = ExplicitVR;
1760          gdcmWarningMacro( "Group 0002 : Explicit Value Representation");
1761       } 
1762       else 
1763       {
1764          Filetype = ImplicitVR;
1765          gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1766                         << "Looks like a bugged Header!");
1767       }
1768       
1769       if ( net2host )
1770       {
1771          SwapCode = 4321;
1772          gdcmWarningMacro( "HostByteOrder != NetworkByteOrder");
1773       }
1774       else 
1775       {
1776          SwapCode = 1234;
1777          gdcmWarningMacro( "HostByteOrder = NetworkByteOrder");
1778       }
1779       
1780       // Position the file position indicator at first tag 
1781       // (i.e. after the file preamble and the "DICM" string).
1782       Fp->seekg(0, std::ios::beg);
1783       Fp->seekg ( 132L, std::ios::beg);
1784       return true;
1785    } // End of DicomV3
1786
1787    // Alas, this is not a DicomV3 file and whatever happens there is no file
1788    // preamble. We can reset the file position indicator to where the data
1789    // is (i.e. the beginning of the file).
1790    gdcmWarningMacro( "Not a DICOM Version3 file");
1791    Fp->seekg(0, std::ios::beg);
1792
1793    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1794    // By clean we mean that the length of the first tag is written down.
1795    // If this is the case and since the length of the first group HAS to be
1796    // four (bytes), then determining the proper swap code is straightforward.
1797
1798    entCur = deb + 4;
1799    // We assume the array of char we are considering contains the binary
1800    // representation of a 32 bits integer. Hence the following dirty
1801    // trick :
1802    s32 = *((uint32_t *)(entCur));
1803
1804    switch( s32 )
1805    {
1806       case 0x00040000 :
1807          SwapCode = 3412;
1808          Filetype = ACR;
1809          return true;
1810       case 0x04000000 :
1811          SwapCode = 4321;
1812          Filetype = ACR;
1813          return true;
1814       case 0x00000400 :
1815          SwapCode = 2143;
1816          Filetype = ACR;
1817          return true;
1818       case 0x00000004 :
1819          SwapCode = 1234;
1820          Filetype = ACR;
1821          return true;
1822       default :
1823          // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1824          // It is time for despaired wild guesses. 
1825          // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1826          //  i.e. the 'group length' element is not present :     
1827          
1828          //  check the supposed-to-be 'group number'
1829          //  in ( 0x0001 .. 0x0008 )
1830          //  to determine ' SwapCode' value .
1831          //  Only 0 or 4321 will be possible 
1832          //  (no oportunity to check for the formerly well known
1833          //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
1834          //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-) 
1835          //  the file IS NOT ACR-NEMA nor DICOM V3
1836          //  Find a trick to tell it the caller...
1837       
1838          s16 = *((uint16_t *)(deb));
1839       
1840          switch ( s16 )
1841          {
1842             case 0x0001 :
1843             case 0x0002 :
1844             case 0x0003 :
1845             case 0x0004 :
1846             case 0x0005 :
1847             case 0x0006 :
1848             case 0x0007 :
1849             case 0x0008 :
1850                SwapCode = 1234;
1851                Filetype = ACR;
1852                return true;
1853             case 0x0100 :
1854             case 0x0200 :
1855             case 0x0300 :
1856             case 0x0400 :
1857             case 0x0500 :
1858             case 0x0600 :
1859             case 0x0700 :
1860             case 0x0800 :
1861                SwapCode = 4321;
1862                Filetype = ACR;
1863                return true;
1864             default :
1865                gdcmWarningMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
1866                Filetype = Unknown;
1867                return false;
1868          }
1869    }
1870 }
1871
1872 /**
1873  * \brief Change the Byte Swap code. 
1874  */
1875 void Document::SwitchByteSwapCode() 
1876 {
1877    gdcmWarningMacro( "Switching Byte Swap code from "<< SwapCode);
1878    if ( SwapCode == 1234 ) 
1879    {
1880       SwapCode = 4321;
1881    }
1882    else if ( SwapCode == 4321 ) 
1883    {
1884       SwapCode = 1234;
1885    }
1886    else if ( SwapCode == 3412 ) 
1887    {
1888       SwapCode = 2143;
1889    }
1890    else if ( SwapCode == 2143 )
1891    {
1892       SwapCode = 3412;
1893    }
1894 }
1895
1896 /**
1897  * \brief  during parsing, Header Elements too long are not loaded in memory 
1898  * @param newSize new size
1899  */
1900 void Document::SetMaxSizeLoadEntry(long newSize) 
1901 {
1902    if ( newSize < 0 )
1903    {
1904       return;
1905    }
1906    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1907    {
1908       MaxSizeLoadEntry = 0xffffffff;
1909       return;
1910    }
1911    MaxSizeLoadEntry = newSize;
1912 }
1913
1914 /**
1915  * \brief   Read the next tag but WITHOUT loading it's value
1916  *          (read the 'Group Number', the 'Element Number',
1917  *          gets the Dict Entry
1918  *          gets the VR, gets the length, gets the offset value)
1919  * @return  On succes the newly created DocEntry, NULL on failure.      
1920  */
1921 DocEntry *Document::ReadNextDocEntry()
1922 {
1923    uint16_t group;
1924    uint16_t elem;
1925
1926    try
1927    {
1928       group = ReadInt16();
1929       elem  = ReadInt16();
1930    }
1931    catch ( FormatError e )
1932    {
1933       // We reached the EOF (or an error occured) therefore 
1934       // header parsing has to be considered as finished.
1935       return 0;
1936    }
1937
1938    // Sometimes file contains groups of tags with reversed endianess.
1939    HandleBrokenEndian(group, elem);
1940
1941    // In 'true DICOM' files Group 0002 is always little endian
1942    if ( HasDCMPreamble )
1943       HandleOutOfGroup0002(group, elem);
1944  
1945    std::string vr = FindDocEntryVR();
1946    std::string realVR = vr;
1947
1948    if( vr == GDCM_UNKNOWN)
1949    {
1950       if ( elem == 0x0000 ) // Group Length
1951          realVR = "UL";     // must be UL
1952       else
1953       {
1954          DictEntry *dictEntry = GetDictEntry(group,elem);
1955          if( dictEntry )
1956             realVR = dictEntry->GetVR();
1957       }
1958    }
1959
1960    DocEntry *newEntry;
1961    if( Global::GetVR()->IsVROfSequence(realVR) )
1962       newEntry = NewSeqEntry(group, elem);
1963    else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
1964       newEntry = NewValEntry(group, elem,vr);
1965    else
1966       newEntry = NewBinEntry(group, elem,vr);
1967
1968    if( vr == GDCM_UNKNOWN )
1969    {
1970       if( Filetype == ExplicitVR )
1971       {
1972          // We thought this was explicit VR, but we end up with an
1973          // implicit VR tag. Let's backtrack.
1974          if ( newEntry->GetGroup() != 0xfffe )
1975          { 
1976             std::string msg;
1977             msg = Util::Format("Entry (%04x,%04x) should be Explicit VR\n", 
1978                           newEntry->GetGroup(), newEntry->GetElement());
1979             gdcmWarningMacro( msg.c_str() );
1980           }
1981       }
1982       newEntry->SetImplicitVR();
1983    }
1984
1985    try
1986    {
1987       FindDocEntryLength(newEntry);
1988    }
1989    catch ( FormatError e )
1990    {
1991       // Call it quits
1992       delete newEntry;
1993       return 0;
1994    }
1995
1996    newEntry->SetOffset(Fp->tellg());  
1997
1998    return newEntry;
1999 }
2000
2001 /**
2002  * \brief   Handle broken private tag from Philips NTSCAN
2003  *          where the endianess is being switch to BigEndian for no
2004  *          apparent reason
2005  * @return  no return
2006  */
2007 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2008 {
2009    // Endian reversion. Some files contain groups of tags with reversed endianess.
2010    static int reversedEndian = 0;
2011    // try to fix endian switching in the middle of headers
2012    if ((group == 0xfeff) && (elem == 0x00e0))
2013    {
2014      // start endian swap mark for group found
2015      reversedEndian++;
2016      SwitchByteSwapCode();
2017      // fix the tag
2018      group = 0xfffe;
2019      elem  = 0xe000;
2020    } 
2021    else if (group == 0xfffe && elem == 0xe00d && reversedEndian) 
2022    {
2023      // end of reversed endian group
2024      reversedEndian--;
2025      SwitchByteSwapCode();
2026    }
2027 }
2028
2029 /**
2030  * \brief   Group 0002 is always coded Little Endian
2031  *          whatever Transfer Syntax is
2032  * @return  no return
2033  */
2034 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2035 {
2036    // Endian reversion. Some files contain groups of tags with reversed endianess.
2037    if ( !Group0002Parsed && group != 0x0002)
2038    {
2039       Group0002Parsed = true;
2040       // we just came out of group 0002
2041       // if Transfer syntax is Big Endian we have to change CheckSwap
2042
2043       std::string ts = GetTransferSyntax();
2044       if ( !Global::GetTS()->IsTransferSyntax(ts) )
2045       {
2046          gdcmWarningMacro("True DICOM File, with NO Tansfer Syntax: " << ts );
2047          return;
2048       }
2049
2050       // Group 0002 is always 'Explicit ...' enven when Transfer Syntax says 'Implicit ..." 
2051
2052       if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian )
2053          {
2054             Filetype = ImplicitVR;
2055          }
2056        
2057       // FIXME Strangely, this works with 
2058       //'Implicit VR Transfer Syntax (GE Private)
2059       if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian )
2060       {
2061          gdcmWarningMacro("Transfer Syntax Name = [" 
2062                         << GetTransferSyntaxName() << "]" );
2063          SwitchByteSwapCode();
2064          group = SwapShort(group);
2065          elem  = SwapShort(elem);
2066       }
2067    }
2068 }
2069
2070 //-----------------------------------------------------------------------------
2071 // Print
2072
2073 //-----------------------------------------------------------------------------
2074 } // end namespace gdcm