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