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