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