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