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