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