]> Creatis software - gdcm.git/blob - src/gdcmFileHelper.cxx
Now the gdcm::File remains unimpaired after writting, in any case.
[gdcm.git] / src / gdcmFileHelper.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmFileHelper.cxx,v $
5   Language:  C++
6
7   Date:      $Date: 2005/05/03 09:51:06 $
8   Version:   $Revision: 1.37 $
9                                                                                 
10   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
11   l'Image). All rights reserved. See Doc/License.txt or
12   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13                                                                                 
14      This software is distributed WITHOUT ANY WARRANTY; without even
15      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
16      PURPOSE.  See the above copyright notices for more information.
17                                                                                 
18 =========================================================================*/
19
20 #include "gdcmFileHelper.h"
21 #include "gdcmGlobal.h"
22 #include "gdcmTS.h"
23 #include "gdcmDocument.h"
24 #include "gdcmDebug.h"
25 #include "gdcmUtil.h"
26 #include "gdcmBinEntry.h"
27 #include "gdcmValEntry.h"
28 #include "gdcmSeqEntry.h"
29 #include "gdcmSQItem.h"
30 #include "gdcmContentEntry.h"
31 #include "gdcmFile.h"
32 #include "gdcmPixelReadConvert.h"
33 #include "gdcmPixelWriteConvert.h"
34 #include "gdcmDocEntryArchive.h"
35 #include "gdcmDictSet.h"
36
37 #include <fstream>
38
39 /*
40 // ----------------------------- WARNING -------------------------
41
42 These lines will be moved to the document-to-be 'User's Guide'
43
44 // To read an image, user needs a gdcm::File
45 gdcm::File *f1 = new gdcm::File(fileName);
46 // user can now check some values
47 std::string v = f1->GetEntryValue(groupNb,ElementNb);
48 // to get the pixels, user needs a gdcm::FileHelper
49 gdcm::FileHelper *fh1 = new gdcm::FileHelper(f1);
50 // user may ask not to convert Palette to RGB
51 uint8_t *pixels = fh1->GetImageDataRaw();
52 int imageLength = fh1->GetImageDataRawSize();
53 // He can now use the pixels, create a new image, ...
54 uint8_t *userPixels = ...
55
56 To re-write the image, user re-uses the gdcm::FileHelper
57
58 fh1->SetImageData( userPixels, userPixelsLength);
59 fh1->SetTypeToRaw(); // Even if it was possible to convert Palette to RGB
60                      // (WriteMode is set)
61  
62 fh1->SetWriteTypeToDcmExpl(); // he wants Explicit Value Representation
63                               // Little Endian is the default
64                               // no other value is allowed
65                                 (-->SetWriteType(ExplicitVR);)
66                                    -->WriteType = ExplicitVR;
67 fh1->Write(newFileName);      // overwrites the file, if any
68
69 // or :
70 fh1->WriteDcmExplVR(newFileName);
71
72
73 // ----------------------------- WARNING -------------------------
74
75 These lines will be moved to the document-to-be 'Developer's Guide'
76
77 WriteMode : WMODE_RAW / WMODE_RGB
78 WriteType : ImplicitVR, ExplicitVR, ACR, ACR_LIBIDO
79
80 fh1->Write(newFileName);
81    SetWriteFileTypeToImplicitVR() / SetWriteFileTypeToExplicitVR();
82    (modifies TransferSyntax)
83    SetWriteToRaw(); / SetWriteToRGB();
84       (modifies, when necessary : photochromatic interpretation, 
85          samples per pixel, Planar configuration, 
86          bits allocated, bits stored, high bit -ACR 24 bits-
87          Pixels element VR, pushes out the LUT )
88    CheckWriteIntegrity();
89       (checks user given pixels length)
90    FileInternal->Write(fileName,WriteType)
91    fp = opens file(fileName);
92    ComputeGroup0002Length(writetype);
93    BitsAllocated 12->16
94       RemoveEntryNoDestroy(palettes, etc)
95       Document::WriteContent(fp, writetype);
96    RestoreWrite();
97       (moves back to the File all the archived elements)
98    RestoreWriteFileType();
99       (pushes back group 0002, with TransferSyntax)
100 */
101
102
103
104
105 namespace gdcm 
106 {
107 //-------------------------------------------------------------------------
108 // Constructor / Destructor
109 /**
110  * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
111  *        file (gdcm::File only deals with the ... header)
112  *        Opens (in read only and when possible) an existing file and checks
113  *        for DICOM compliance. Returns NULL on failure.
114  *        It will be up to the user to load the pixels into memory
115  * \note  the in-memory representation of all available tags found in
116  *        the DICOM header is post-poned to first header information access.
117  *        This avoid a double parsing of public part of the header when
118  *        one sets an a posteriori shadow dictionary (efficiency can be
119  *        seen as a side effect).   
120  */
121 FileHelper::FileHelper( )
122 {
123    FileInternal = new File( );
124    SelfHeader = true;
125    Initialize();
126 }
127
128 /**
129  * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
130  *        file (File only deals with the ... header)
131  *        Opens (in read only and when possible) an existing file and checks
132  *        for DICOM compliance. Returns NULL on failure.
133  *        It will be up to the user to load the pixels into memory
134  * \note  the in-memory representation of all available tags found in
135  *        the DICOM header is post-poned to first header information access.
136  *        This avoid a double parsing of public part of the header when
137  *        user sets an a posteriori shadow dictionary (efficiency can be
138  *        seen as a side effect).   
139  * @param header already built Header
140  */
141 FileHelper::FileHelper(File *header)
142 {
143    FileInternal = header;
144    SelfHeader = false;
145    Initialize();
146 }
147
148 /**
149  * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
150  *        file (gdcm::File only deals with the ... header)
151  *        Opens (in read only and when possible) an existing file and checks
152  *        for DICOM compliance. Returns NULL on failure.
153  *        It will be up to the user to load the pixels into memory
154  * \note  the in-memory representation of all available tags found in
155  *        the DICOM header is post-poned to first header information access.
156  *        This avoid a double parsing of public part of the header when
157  *        one sets an a posteriori shadow dictionary (efficiency can be
158  *        seen as a side effect).   
159  * @param filename file to be opened for parsing
160  */
161 FileHelper::FileHelper(std::string const &filename )
162 {
163    FileInternal = new File( filename );
164    SelfHeader = true;
165    Initialize();
166 }
167
168 /**
169  * \brief canonical destructor
170  * \note  If the header (gdcm::File) was created by the FileHelper constructor,
171  *        it is destroyed by the FileHelper
172  */
173 FileHelper::~FileHelper()
174
175    if( PixelReadConverter )
176    {
177       delete PixelReadConverter;
178    }
179    if( PixelWriteConverter )
180    {
181       delete PixelWriteConverter;
182    }
183    if( Archive )
184    {
185       delete Archive;
186    }
187
188    if( SelfHeader )
189    {
190       delete FileInternal;
191    }
192    FileInternal = 0;
193 }
194
195 //-----------------------------------------------------------------------------
196 // Public
197 /**
198  * \brief   Accesses an existing DocEntry (i.e. a Dicom Element)
199  *          through it's (group, element) and modifies it's content with
200  *          the given value.
201  * @param   content new value (string) to substitute with
202  * @param   group  group number of the Dicom Element to modify
203  * @param   elem element number of the Dicom Element to modify
204  * \return  false if DocEntry not found
205  */
206 bool FileHelper::SetValEntry(std::string const &content,
207                              uint16_t group, uint16_t elem)
208
209    return FileInternal->SetValEntry(content, group, elem);
210 }
211
212
213 /**
214  * \brief   Accesses an existing DocEntry (i.e. a Dicom Element)
215  *          through it's (group, element) and modifies it's content with
216  *          the given value.
217  * @param   content new value (void*  -> uint8_t*) to substitute with
218  * @param   lgth new value length
219  * @param   group  group number of the Dicom Element to modify
220  * @param   elem element number of the Dicom Element to modify
221  * \return  false if DocEntry not found
222  */
223 bool FileHelper::SetBinEntry(uint8_t *content, int lgth,
224                              uint16_t group, uint16_t elem)
225 {
226    return FileInternal->SetBinEntry(content, lgth, group, elem);
227 }
228
229 /**
230  * \brief   Modifies the value of a given DocEntry (Dicom entry)
231  *          when it exists. Creates it with the given value when unexistant.
232  * @param   content (string)value to be set
233  * @param   group   Group number of the Entry 
234  * @param   elem  Element number of the Entry
235  * \return  pointer to the modified/created Dicom entry (NULL when creation
236  *          failed).
237  */ 
238 ValEntry *FileHelper::InsertValEntry(std::string const &content,
239                                      uint16_t group, uint16_t elem)
240 {
241    return FileInternal->InsertValEntry(content,group,elem);
242 }
243
244 /**
245  * \brief   Modifies the value of a given DocEntry (Dicom entry)
246  *          when it exists. Creates it with the given value when unexistant.
247  *          A copy of the binArea is made to be kept in the Document.
248  * @param   binArea (binary)value to be set
249  * @param   lgth new value length
250  * @param   group   Group number of the Entry 
251  * @param   elem  Element number of the Entry
252  * \return  pointer to the modified/created Dicom entry (NULL when creation
253  *          failed).
254  */
255 BinEntry *FileHelper::InsertBinEntry(uint8_t *binArea, int lgth,
256                                      uint16_t group, uint16_t elem)
257 {
258    return FileInternal->InsertBinEntry(binArea, lgth, group, elem);
259 }
260
261 /**
262  * \brief   Modifies the value of a given DocEntry (Dicom entry)
263  *          when it exists. Creates it, empty (?!) when unexistant.
264  * @param   group   Group number of the Entry 
265  * @param   elem  Element number of the Entry
266  * \return  pointer to the modified/created Dicom entry (NULL when creation
267  *          failed).
268  */
269 SeqEntry *FileHelper::InsertSeqEntry(uint16_t group, uint16_t elem)
270 {
271    return FileInternal->InsertSeqEntry(group, elem);
272 }
273
274 /**
275  * \brief   Get the size of the image data
276  *          If the image can be RGB (with a lut or by default), the size 
277  *          corresponds to the RGB image
278  *         (use GetImageDataRawSize if you want to be sure to get *only*
279  *          the size of the pixels)
280  * @return  The image size
281  */
282 size_t FileHelper::GetImageDataSize()
283 {
284    if ( PixelWriteConverter->GetUserData() )
285    {
286       return PixelWriteConverter->GetUserDataSize();
287    }
288    return PixelReadConverter->GetRGBSize();
289 }
290
291 /**
292  * \brief   Get the size of the image data
293  *          If the image could be converted to RGB using a LUT, 
294  *          this transformation is not taken into account by GetImageDataRawSize
295  *          (use GetImageDataSize if you wish)
296  * @return  The raw image size
297  */
298 size_t FileHelper::GetImageDataRawSize()
299 {
300    if ( PixelWriteConverter->GetUserData() )
301    {
302       return PixelWriteConverter->GetUserDataSize();
303    }
304    return PixelReadConverter->GetRawSize();
305 }
306
307 /**
308  * \brief   - Allocates necessary memory,
309  *          - Reads the pixels from disk (uncompress if necessary),
310  *          - Transforms YBR pixels, if any, into RGB pixels,
311  *          - Transforms 3 planes R, G, B, if any, into a single RGB Plane
312  *          - Transforms single Grey plane + 3 Palettes into a RGB Plane
313  *          - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
314  * @return  Pointer to newly allocated pixel data.
315  *          NULL if alloc fails 
316  */
317 uint8_t *FileHelper::GetImageData()
318 {
319    if ( PixelWriteConverter->GetUserData() )
320    {
321       return PixelWriteConverter->GetUserData();
322    }
323
324    if ( ! GetRaw() )
325    {
326       // If the decompression failed nothing can be done.
327       return 0;
328    }
329
330    if ( FileInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
331    {
332       return PixelReadConverter->GetRGB();
333    }
334    else
335    {
336       // When no LUT or LUT conversion fails, return the Raw
337       return PixelReadConverter->GetRaw();
338    }
339 }
340
341 /**
342  * \brief   Allocates necessary memory, 
343  *          Transforms YBR pixels (if any) into RGB pixels
344  *          Transforms 3 planes R, G, B  (if any) into a single RGB Plane
345  *          Copies the pixel data (image[s]/volume[s]) to newly allocated zone. 
346  *          DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
347  * @return  Pointer to newly allocated pixel data.
348  *          NULL if alloc fails 
349  */
350 uint8_t *FileHelper::GetImageDataRaw ()
351 {
352    return GetRaw();
353 }
354
355 /**
356  * \brief
357  *          Read the pixels from disk (uncompress if necessary),
358  *          Transforms YBR pixels, if any, into RGB pixels
359  *          Transforms 3 planes R, G, B, if any, into a single RGB Plane
360  *          Transforms single Grey plane + 3 Palettes into a RGB Plane   
361  *          Copies at most MaxSize bytes of pixel data to caller allocated
362  *          memory space.
363  * \warning This function allows people that want to build a volume
364  *          from an image stack *not to* have, first to get the image pixels, 
365  *          and then move them to the volume area.
366  *          It's absolutely useless for any VTK user since vtk chooses 
367  *          to invert the lines of an image, that is the last line comes first
368  *          (for some axis related reasons?). Hence he will have 
369  *          to load the image line by line, starting from the end.
370  *          VTK users have to call GetImageData
371  *     
372  * @param   destination Address (in caller's memory space) at which the
373  *          pixel data should be copied
374  * @param   maxSize Maximum number of bytes to be copied. When MaxSize
375  *          is not sufficient to hold the pixel data the copy is not
376  *          executed (i.e. no partial copy).
377  * @return  On success, the number of bytes actually copied. Zero on
378  *          failure e.g. MaxSize is lower than necessary.
379  */
380 size_t FileHelper::GetImageDataIntoVector (void *destination, size_t maxSize)
381 {
382    if ( ! GetRaw() )
383    {
384       // If the decompression failed nothing can be done.
385       return 0;
386    }
387
388    if ( FileInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
389    {
390       if ( PixelReadConverter->GetRGBSize() > maxSize )
391       {
392          gdcmWarningMacro( "Pixel data bigger than caller's expected MaxSize");
393          return 0;
394       }
395       memcpy( destination,
396               (void*)PixelReadConverter->GetRGB(),
397               PixelReadConverter->GetRGBSize() );
398       return PixelReadConverter->GetRGBSize();
399    }
400
401    // Either no LUT conversion necessary or LUT conversion failed
402    if ( PixelReadConverter->GetRawSize() > maxSize )
403    {
404       gdcmWarningMacro( "Pixel data bigger than caller's expected MaxSize");
405       return 0;
406    }
407    memcpy( destination,
408            (void *)PixelReadConverter->GetRaw(),
409            PixelReadConverter->GetRawSize() );
410    return PixelReadConverter->GetRawSize();
411 }
412
413 /**
414  * \brief   Points the internal pointer to the callers inData
415  *          image representation, BUT WITHOUT COPYING THE DATA.
416  *          'image' Pixels are presented as C-like 2D arrays : line per line.
417  *          'volume'Pixels are presented as C-like 3D arrays : plane per plane 
418  * \warning Since the pixels are not copied, it is the caller's responsability
419  *          not to deallocate its data before gdcm uses them (e.g. with
420  *          the Write() method )
421  * @param inData user supplied pixel area (uint8_t* is just for the compiler.
422  *               user is allowed to pass any kind of pixelsn since the size is
423  *               given in bytes) 
424  * @param expectedSize total image size, *in Bytes*
425  */
426 void FileHelper::SetImageData(uint8_t *inData, size_t expectedSize)
427 {
428    SetUserData(inData, expectedSize);
429 }
430
431 /**
432  * \brief   Set the image data defined by the user
433  * \warning When writting the file, this data are get as default data to write
434  * @param inData user supplied pixel area (uint8_t* is just for the compiler.
435  *               user is allowed to pass any kind of pixels since the size is
436  *               given in bytes) 
437  * @param expectedSize total image size, *in Bytes* 
438  */
439 void FileHelper::SetUserData(uint8_t *inData, size_t expectedSize)
440 {
441    PixelWriteConverter->SetUserData(inData, expectedSize);
442 }
443
444 /**
445  * \brief   Get the image data defined by the user
446  * \warning When writting the file, this data are get as default data to write
447  */
448 uint8_t *FileHelper::GetUserData()
449 {
450    return PixelWriteConverter->GetUserData();
451 }
452
453 /**
454  * \brief   Get the image data size defined by the user
455  * \warning When writting the file, this data are get as default data to write
456  */
457 size_t FileHelper::GetUserDataSize()
458 {
459    return PixelWriteConverter->GetUserDataSize();
460 }
461
462 /**
463  * \brief   Get the image data from the file.
464  *          If a LUT is found, the data are expanded to be RGB
465  */
466 uint8_t *FileHelper::GetRGBData()
467 {
468    return PixelReadConverter->GetRGB();
469 }
470
471 /**
472  * \brief   Get the image data size from the file.
473  *          If a LUT is found, the data are expanded to be RGB
474  */
475 size_t FileHelper::GetRGBDataSize()
476 {
477    return PixelReadConverter->GetRGBSize();
478 }
479
480 /**
481  * \brief   Get the image data from the file.
482  *          Even when a LUT is found, the data are not expanded to RGB!
483  */
484 uint8_t *FileHelper::GetRawData()
485 {
486    return PixelReadConverter->GetRaw();
487 }
488
489 /**
490  * \brief   Get the image data size from the file.
491  *          Even when a LUT is found, the data are not expanded to RGB!
492  */
493 size_t FileHelper::GetRawDataSize()
494 {
495    return PixelReadConverter->GetRawSize();
496 }
497
498 /**
499  * \brief Access to the underlying \ref PixelReadConverter RGBA LUT
500  */
501 uint8_t* FileHelper::GetLutRGBA()
502 {
503    return PixelReadConverter->GetLutRGBA();
504 }
505
506 /**
507  * \brief Writes on disk A SINGLE Dicom file
508  *        NO test is performed on  processor "Endiannity".
509  *        It's up to the user to call his Reader properly
510  * @param fileName name of the file to be created
511  *                 (any already existing file is over written)
512  * @return false if write fails
513  */
514 bool FileHelper::WriteRawData(std::string const &fileName)
515 {
516    std::ofstream fp1(fileName.c_str(), std::ios::out | std::ios::binary );
517    if (!fp1)
518    {
519       gdcmWarningMacro( "Fail to open (write) file:" << fileName.c_str());
520       return false;
521    }
522
523    if( PixelWriteConverter->GetUserData() )
524    {
525       fp1.write( (char *)PixelWriteConverter->GetUserData(), 
526                  PixelWriteConverter->GetUserDataSize() );
527    }
528    else if ( PixelReadConverter->GetRGB() )
529    {
530       fp1.write( (char *)PixelReadConverter->GetRGB(), 
531                  PixelReadConverter->GetRGBSize());
532    }
533    else if ( PixelReadConverter->GetRaw() )
534    {
535       fp1.write( (char *)PixelReadConverter->GetRaw(), 
536                  PixelReadConverter->GetRawSize());
537    }
538    else
539    {
540       gdcmErrorMacro( "Nothing written." );
541    }
542
543    fp1.close();
544
545    return true;
546 }
547
548 /**
549  * \brief Writes on disk A SINGLE Dicom file, 
550  *        using the Implicit Value Representation convention
551  *        NO test is performed on  processor "Endianity".
552  * @param fileName name of the file to be created
553  *                 (any already existing file is overwritten)
554  * @return false if write fails
555  */
556
557 bool FileHelper::WriteDcmImplVR (std::string const &fileName)
558 {
559    SetWriteTypeToDcmImplVR();
560    return Write(fileName);
561 }
562
563 /**
564 * \brief Writes on disk A SINGLE Dicom file, 
565  *        using the Explicit Value Representation convention
566  *        NO test is performed on  processor "Endiannity". 
567  * @param fileName name of the file to be created
568  *                 (any already existing file is overwritten)
569  * @return false if write fails
570  */
571
572 bool FileHelper::WriteDcmExplVR (std::string const &fileName)
573 {
574    SetWriteTypeToDcmExplVR();
575    return Write(fileName);
576 }
577
578 /**
579  * \brief Writes on disk A SINGLE Dicom file, 
580  *        using the ACR-NEMA convention
581  *        NO test is performed on  processor "Endiannity".
582  *        (a l'attention des logiciels cliniques 
583  *        qui ne prennent en entrée QUE des images ACR ...
584  * \warning if a DICOM_V3 header is supplied,
585  *         groups < 0x0008 and shadow groups are ignored
586  * \warning NO TEST is performed on processor "Endiannity".
587  * @param fileName name of the file to be created
588  *                 (any already existing file is overwritten)
589  * @return false if write fails
590  */
591
592 bool FileHelper::WriteAcr (std::string const &fileName)
593 {
594    SetWriteTypeToAcr();
595    return Write(fileName);
596 }
597
598 /**
599  * \brief Writes on disk A SINGLE Dicom file, 
600  * @param fileName name of the file to be created
601  *                 (any already existing file is overwritten)
602  * @return false if write fails
603  */
604 bool FileHelper::Write(std::string const &fileName)
605 {
606    switch(WriteType)
607    {
608       case ImplicitVR:
609          SetWriteFileTypeToImplicitVR();
610          break;
611       case Unknown:  // should never happen; ExplicitVR is the default value
612       case ExplicitVR:
613          SetWriteFileTypeToExplicitVR();
614          break;
615       case ACR:
616       case ACR_LIBIDO:
617       // NOTHING is done here just for LibIDO.
618       // Just to avoid further trouble if user creates a file ex-nihilo,
619       // wants to write it as an ACR-NEMA file,
620       // and forgets to create any Entry belonging to group 0008
621       // (shame on him !)
622       // We add Recognition Code (RET)
623         if ( ! FileInternal->GetValEntry(0x0008, 0x0010) )
624             FileInternal->InsertValEntry("", 0x0008, 0x0010);
625          SetWriteFileTypeToACR();
626          SetWriteFileTypeToImplicitVR();
627          break;
628    }
629    CheckMandatoryElements();
630
631    // --------------------------------------------------------------
632    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
633    //
634    // if recognition code tells us we dealt with a LibIDO image
635    // we reproduce on disk the switch between lineNumber and columnNumber
636    // just before writting ...
637    /// \todo the best trick would be *change* the recognition code
638    ///       but pb expected if user deals with, e.g. COMPLEX images
639    
640    if( WriteType == ACR_LIBIDO )
641    {
642       SetWriteToLibido();
643    }
644    else
645    {
646       SetWriteToNoLibido();
647    }
648    // ----------------- End of Special Patch ----------------
649   
650    switch(WriteMode)
651    {
652       case WMODE_RAW :
653          SetWriteToRaw(); // modifies and pushes to the archive, when necessary
654          break;
655       case WMODE_RGB :
656          SetWriteToRGB(); // modifies and pushes to the archive, when necessary
657          break;
658    }
659
660    bool check = CheckWriteIntegrity(); // verifies length
661    if(check)
662    {
663       check = FileInternal->Write(fileName,WriteType);
664    }
665
666    RestoreWrite();
667    RestoreWriteFileType();
668    RestoreWriteMandatory();
669
670    // --------------------------------------------------------------
671    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
672    // 
673    // ...and we restore the header to be Dicom Compliant again 
674    // just after writting
675    RestoreWriteOfLibido();
676    // ----------------- End of Special Patch ----------------
677
678    return check;
679 }
680
681 //-----------------------------------------------------------------------------
682 // Protected
683 /**
684  * \brief Checks the write integrity
685  *
686  * The tests made are :
687  *  - verify the size of the image to write with the possible write
688  *    when the user set an image data
689  * @return true if check is successfull
690  */
691 bool FileHelper::CheckWriteIntegrity()
692 {
693    if(PixelWriteConverter->GetUserData())
694    {
695       int numberBitsAllocated = FileInternal->GetBitsAllocated();
696       if ( numberBitsAllocated == 0 || numberBitsAllocated == 12 )
697       {
698          numberBitsAllocated = 16;
699       }
700
701       size_t decSize = FileInternal->GetXSize()
702                      * FileInternal->GetYSize() 
703                      * FileInternal->GetZSize()
704                      * FileInternal->GetSamplesPerPixel()
705                      * ( numberBitsAllocated / 8 );
706       size_t rgbSize = decSize;
707       if( FileInternal->HasLUT() )
708          rgbSize = decSize * 3;
709
710       switch(WriteMode)
711       {
712          case WMODE_RAW :
713             if( decSize!=PixelWriteConverter->GetUserDataSize() )
714             {
715                gdcmWarningMacro( "Data size (Raw) is incorrect. Should be " 
716                            << decSize << " / Found :" 
717                            << PixelWriteConverter->GetUserDataSize() );
718                return false;
719             }
720             break;
721          case WMODE_RGB :
722             if( rgbSize!=PixelWriteConverter->GetUserDataSize() )
723             {
724                gdcmWarningMacro( "Data size (RGB) is incorrect. Should be " 
725                           << decSize << " / Found " 
726                           << PixelWriteConverter->GetUserDataSize() );
727                return false;
728             }
729             break;
730       }
731    }   
732    return true;
733 }
734
735 /**
736  * \brief Updates the File to write RAW data (as opposed to RGB data)
737  *       (modifies, when necessary, photochromatic interpretation, 
738  *       bits allocated, Pixels element VR)
739  */ 
740 void FileHelper::SetWriteToRaw()
741 {
742    if( FileInternal->GetNumberOfScalarComponents() == 3 
743     && !FileInternal->HasLUT())
744    {
745       SetWriteToRGB();
746    } 
747    else
748    {
749       ValEntry *photInt = CopyValEntry(0x0028,0x0004);
750       if(FileInternal->HasLUT())
751       {
752          photInt->SetValue("PALETTE COLOR ");
753       }
754       else
755       {
756          photInt->SetValue("MONOCHROME2 ");
757       }
758
759       PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
760                                        PixelReadConverter->GetRawSize());
761
762       std::string vr = "OB";
763       if( FileInternal->GetBitsAllocated()>8 )
764          vr = "OW";
765       if( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files 
766          vr = "OB";
767       BinEntry *pixel = 
768          CopyBinEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
769       pixel->SetValue(GDCM_BINLOADED);
770       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
771       pixel->SetLength(PixelWriteConverter->GetDataSize());
772
773       Archive->Push(photInt);
774       Archive->Push(pixel);
775    }
776 }
777
778 /**
779  * \brief Updates the File to write RGB data (as opposed to RAW data)
780  *       (modifies, when necessary, photochromatic interpretation, 
781  *       samples per pixel, Planar configuration, 
782  *       bits allocated, bits stored, high bit -ACR 24 bits-
783  *       Pixels element VR, pushes out the LUT, )
784  */ 
785 void FileHelper::SetWriteToRGB()
786 {
787    if(FileInternal->GetNumberOfScalarComponents()==3)
788    {
789       PixelReadConverter->BuildRGBImage();
790       
791       ValEntry *spp = CopyValEntry(0x0028,0x0002);
792       spp->SetValue("3 ");
793
794       ValEntry *planConfig = CopyValEntry(0x0028,0x0006);
795       planConfig->SetValue("0 ");
796
797       ValEntry *photInt = CopyValEntry(0x0028,0x0004);
798       photInt->SetValue("RGB ");
799
800       if(PixelReadConverter->GetRGB())
801       {
802          PixelWriteConverter->SetReadData(PixelReadConverter->GetRGB(),
803                                           PixelReadConverter->GetRGBSize());
804       }
805       else // Raw data
806       {
807          PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
808                                           PixelReadConverter->GetRawSize());
809       }
810
811       std::string vr = "OB";
812       if( FileInternal->GetBitsAllocated()>8 )
813          vr = "OW";
814       if( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files 
815          vr = "OB";
816       BinEntry *pixel = 
817          CopyBinEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
818       pixel->SetValue(GDCM_BINLOADED);
819       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
820       pixel->SetLength(PixelWriteConverter->GetDataSize());
821
822       Archive->Push(spp);
823       Archive->Push(planConfig);
824       Archive->Push(photInt);
825       Archive->Push(pixel);
826
827       // Remove any LUT
828       Archive->Push(0x0028,0x1101);
829       Archive->Push(0x0028,0x1102);
830       Archive->Push(0x0028,0x1103);
831       Archive->Push(0x0028,0x1201);
832       Archive->Push(0x0028,0x1202);
833       Archive->Push(0x0028,0x1203);
834
835       // For old '24 Bits' ACR-NEMA
836       // Thus, we have a RGB image and the bits allocated = 24 and 
837       // samples per pixels = 1 (in the read file)
838       if(FileInternal->GetBitsAllocated()==24) 
839       {
840          ValEntry *bitsAlloc = CopyValEntry(0x0028,0x0100);
841          bitsAlloc->SetValue("8 ");
842
843          ValEntry *bitsStored = CopyValEntry(0x0028,0x0101);
844          bitsStored->SetValue("8 ");
845
846          ValEntry *highBit = CopyValEntry(0x0028,0x0102);
847          highBit->SetValue("7 ");
848
849          Archive->Push(bitsAlloc);
850          Archive->Push(bitsStored);
851          Archive->Push(highBit);
852       }
853    }
854    else
855    {
856       SetWriteToRaw();
857    }
858 }
859
860 /**
861  * \brief Restore the File write mode  
862  */ 
863 void FileHelper::RestoreWrite()
864 {
865    Archive->Restore(0x0028,0x0002);
866    Archive->Restore(0x0028,0x0004);
867    Archive->Restore(0x0028,0x0006);
868    Archive->Restore(GetFile()->GetGrPixel(),GetFile()->GetNumPixel());
869
870    // For old ACR-NEMA (24 bits problem)
871    Archive->Restore(0x0028,0x0100);
872    Archive->Restore(0x0028,0x0101);
873    Archive->Restore(0x0028,0x0102);
874
875    // For the LUT
876    Archive->Restore(0x0028,0x1101);
877    Archive->Restore(0x0028,0x1102);
878    Archive->Restore(0x0028,0x1103);
879    Archive->Restore(0x0028,0x1201);
880    Archive->Restore(0x0028,0x1202);
881    Archive->Restore(0x0028,0x1203);
882
883    // group 0002 may be pushed out for ACR-NEMA writting purposes 
884    Archive->Restore(0x0002,0x0000);
885    Archive->Restore(0x0002,0x0001);
886    Archive->Restore(0x0002,0x0002);
887    Archive->Restore(0x0002,0x0003);
888    Archive->Restore(0x0002,0x0010);
889    Archive->Restore(0x0002,0x0012);
890    Archive->Restore(0x0002,0x0013);
891    Archive->Restore(0x0002,0x0016);
892    Archive->Restore(0x0002,0x0100);
893    Archive->Restore(0x0002,0x0102);
894 }
895
896 /**
897  * \brief Pushes out the whole group 0002
898  *        FIXME : better, set a flag to tell the writer not to write it ...
899  *        FIXME : method should probably have an other name !
900  *                SetWriteFileTypeToACR is NOT opposed to 
901  *                SetWriteFileTypeToExplicitVR and SetWriteFileTypeToImplicitVR
902  */ 
903 void FileHelper::SetWriteFileTypeToACR()
904 {
905    Archive->Push(0x0002,0x0000);
906    Archive->Push(0x0002,0x0001);
907    Archive->Push(0x0002,0x0002);
908    Archive->Push(0x0002,0x0003);
909    Archive->Push(0x0002,0x0010);
910    Archive->Push(0x0002,0x0012);
911    Archive->Push(0x0002,0x0013);
912    Archive->Push(0x0002,0x0016);
913    Archive->Push(0x0002,0x0100);
914    Archive->Push(0x0002,0x0102);
915 }
916
917 /**
918  * \brief Sets in the File the TransferSyntax to 'Explicit VR Little Endian"   
919  */ 
920 void FileHelper::SetWriteFileTypeToExplicitVR()
921 {
922    std::string ts = Util::DicomString( 
923       Global::GetTS()->GetSpecialTransferSyntax(TS::ExplicitVRLittleEndian) );
924
925    ValEntry *tss = CopyValEntry(0x0002,0x0010);
926    tss->SetValue(ts);
927
928    Archive->Push(tss);
929 }
930
931 /**
932  * \brief Sets in the File the TransferSyntax to 'Implicit VR Little Endian"   
933  */ 
934 void FileHelper::SetWriteFileTypeToImplicitVR()
935 {
936    std::string ts = Util::DicomString(
937       Global::GetTS()->GetSpecialTransferSyntax(TS::ImplicitVRLittleEndian) );
938
939    ValEntry *tss = CopyValEntry(0x0002,0x0010);
940    tss->SetValue(ts);
941
942    Archive->Push(tss);
943 }
944
945
946 /**
947  * \brief Restore in the File the initial group 0002
948  */ 
949 void FileHelper::RestoreWriteFileType()
950 {
951 }
952
953 /**
954  * \brief Set the Write not to Libido format
955  */ 
956 void FileHelper::SetWriteToLibido()
957 {
958    ValEntry *oldRow = dynamic_cast<ValEntry *>
959                 (FileInternal->GetDocEntry(0x0028, 0x0010));
960    ValEntry *oldCol = dynamic_cast<ValEntry *>
961                 (FileInternal->GetDocEntry(0x0028, 0x0011));
962    
963    if( oldRow && oldCol )
964    {
965       std::string rows, columns; 
966
967       ValEntry *newRow=new ValEntry(oldRow->GetDictEntry());
968       ValEntry *newCol=new ValEntry(oldCol->GetDictEntry());
969
970       newRow->Copy(oldCol);
971       newCol->Copy(oldRow);
972
973       newRow->SetValue(oldCol->GetValue());
974       newCol->SetValue(oldRow->GetValue());
975
976       Archive->Push(newRow);
977       Archive->Push(newCol);
978    }
979
980    ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
981    libidoCode->SetValue("ACRNEMA_LIBIDO_1.1");
982    Archive->Push(libidoCode);
983 }
984
985 /**
986  * \brief Set the Write not to No Libido format
987  */ 
988 void FileHelper::SetWriteToNoLibido()
989 {
990    ValEntry *recCode = dynamic_cast<ValEntry *>
991                 (FileInternal->GetDocEntry(0x0008,0x0010));
992    if( recCode )
993    {
994       if( recCode->GetValue() == "ACRNEMA_LIBIDO_1.1" )
995       {
996          ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
997          libidoCode->SetValue("");
998          Archive->Push(libidoCode);
999       }
1000    }
1001 }
1002
1003 /**
1004  * \brief Restore the Write format
1005  */ 
1006 void FileHelper::RestoreWriteOfLibido()
1007 {
1008    Archive->Restore(0x0028,0x0010);
1009    Archive->Restore(0x0028,0x0011);
1010    Archive->Restore(0x0008,0x0010);
1011
1012    // Restore 'LibIDO-special' entries, if any
1013    Archive->Restore(0x0028,0x0015);
1014    Archive->Restore(0x0028,0x0016);
1015    Archive->Restore(0x0028,0x0017);
1016    Archive->Restore(0x0028,0x00199);
1017 }
1018
1019 /**
1020  * \brief Duplicates a ValEntry or creates it.
1021  * @param   group   Group number of the Entry 
1022  * @param   elem  Element number of the Entry
1023  * \return  pointer to the new Val Entry (NULL when creation failed).          
1024  */ 
1025 ValEntry *FileHelper::CopyValEntry(uint16_t group, uint16_t elem)
1026 {
1027    DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
1028    ValEntry *newE;
1029
1030    if( oldE )
1031    {
1032       newE = new ValEntry(oldE->GetDictEntry());
1033       newE->Copy(oldE);
1034    }
1035    else
1036    {
1037       newE = GetFile()->NewValEntry(group, elem);
1038    }
1039
1040    return newE;
1041 }
1042
1043 /**
1044  * \brief   Duplicates a BinEntry or creates it.
1045  * @param   group   Group number of the Entry 
1046  * @param   elem  Element number of the Entry
1047  * @param   vr  Value Representation of the Entry
1048  *          FIXME : what is it used for?
1049  * \return  pointer to the new Bin Entry (NULL when creation failed).
1050  */ 
1051 BinEntry *FileHelper::CopyBinEntry(uint16_t group, uint16_t elem,
1052                                    const std::string &vr)
1053 {
1054    DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
1055    BinEntry *newE;
1056
1057    if( oldE ) 
1058       if( oldE->GetVR()!=vr )
1059          oldE = NULL;
1060
1061    if( oldE )
1062    {
1063       newE = new BinEntry(oldE->GetDictEntry());
1064       newE->Copy(oldE);
1065    }
1066    else
1067    {
1068       newE = GetFile()->NewBinEntry(group, elem, vr);
1069    }
1070
1071    return newE;
1072 }
1073
1074 /**
1075  * \brief   This method is called automatically, just before writting
1076  *         in order to produce a 'True Dicom V3' image
1077  *         We cannot know *how* the user made the File (reading an old ACR-NEMA
1078  *         file or a not very clean DICOM file ...) 
1079  *          
1080  *          Just before writting :
1081  *             - we check the Entries
1082  *             - we create the mandatory entries if they are missing
1083  *             - we modify the values if necessary
1084  *             - we push the sensitive entries to the Archive
1085  *          The writing process will restore the entries as they where before 
1086  *          entering FileHelper::CheckMandatoryElements, so the user will always
1087  *          see the entries just as he left them.
1088  * 
1089  * \todo : - warn the user if we had to add some entries :
1090  *         even if a mandatory entry is missing, we add it, with a default value
1091  *         (we don't want to give up the writting process if user forgot to
1092  *         specify Lena's Patient ID, for instance ...)
1093  *         - read the whole PS 3.3 Part of DICOM  (890 pages)
1094  *         and write a *full* checker (probably one method per Modality ...)
1095  *         Any contribution is welcome. 
1096  *         - write a user callable full checker, to allow post reading
1097  *         and/or pre writting image consistency check.           
1098  */ 
1099  
1100 void FileHelper::CheckMandatoryElements()
1101 {
1102    // just to remember : 'official' 0002 group
1103
1104    //0002 0000 UL 1 Meta Group Length
1105    //0002 0001 OB 1 File Meta Information Version
1106    //0002 0002 UI 1 Media Stored SOP Class UID
1107    //0002 0003 UI 1 Media Stored SOP Instance UID
1108    //0002 0010 UI 1 Transfer Syntax UID
1109    //0002 0012 UI 1 Implementation Class UID
1110    //0002 0013 SH 1 Implementation Version Name
1111    //0002 0016 AE 1 Source Application Entity Title
1112    //0002 0100 UI 1 Private Information Creator
1113    //0002 0102 OB 1 Private Information
1114   
1115    // Create them if not found
1116    // Always modify the value
1117    // Push the entries to the archive.
1118    ValEntry *e_0002_0000 = CopyValEntry(0x0002,0x0000);
1119       e_0002_0000->SetValue("0"); // for the moment
1120       Archive->Push(e_0002_0000);
1121   
1122    BinEntry *e_0002_0001 = CopyBinEntry(0x0002,0x0001, "OB");
1123       e_0002_0001->SetBinArea((uint8_t*)Util::GetFileMetaInformationVersion(),
1124                                false);
1125       e_0002_0001->SetLength(2);
1126       Archive->Push(e_0002_0001);
1127
1128    // 'Media Stored SOP Class UID' 
1129    ValEntry *e_0002_0002 = CopyValEntry(0x0002,0x0002);
1130       // [Secondary Capture Image Storage]
1131       e_0002_0002->SetValue("1.2.840.10008.5.1.4.1.1.7"); 
1132       Archive->Push(e_0002_0002);
1133  
1134    // 'Media Stored SOP Instance UID'   
1135    ValEntry *e_0002_0003 = CopyValEntry(0x0002,0x0003);
1136       e_0002_0003->SetValue(Util::CreateUniqueUID());
1137       Archive->Push(e_0002_0003); 
1138
1139    // 'Implementation Class UID'
1140    ValEntry *e_0002_0012 = CopyValEntry(0x0002,0x0012);
1141       e_0002_0012->SetValue(Util::CreateUniqueUID());
1142       Archive->Push(e_0002_0012); 
1143
1144    // 'Implementation Version Name'
1145    ValEntry *e_0002_0013 = CopyValEntry(0x0002,0x0013);
1146       e_0002_0013->SetValue("GDCM 1.0");
1147       Archive->Push(e_0002_0013);
1148
1149    //'Source Application Entity Title' Not Mandatory
1150    //ValEntry *e_0002_0016 = CopyValEntry(0x0002,0x0016);
1151    //   e_0002_0016->SetValue("1.2.840.10008.5.1.4.1.1.7");
1152    //   Archive->Push(e_0002_0016);
1153
1154    // Push out 'LibIDO-special' entries, if any
1155    Archive->Push(0x0028,0x0015);
1156    Archive->Push(0x0028,0x0016);
1157    Archive->Push(0x0028,0x0017);
1158    Archive->Push(0x0028,0x00199);
1159
1160    // Deal with the pb of (Bits Stored = 12)
1161    // - we're gonna write the image as Bits Stored = 16
1162    if ( FileInternal->GetEntryValue(0x0028,0x0100) ==  "12")
1163    {
1164       ValEntry *e_0028_0100 = CopyValEntry(0x0028,0x0100);
1165       e_0028_0100->SetValue("16");
1166       Archive->Push(e_0028_0100);
1167    }
1168
1169    // --- Check UID-related Entries ---
1170
1171    // If 'SOP Class UID' exists ('true DICOM' image)
1172    // we create the 'Source Image Sequence' SeqEntry
1173    // to hold informations about the Source Image
1174
1175    ValEntry *e_0008_0016 = FileInternal->GetValEntry(0x0008, 0x0016);
1176    if ( e_0008_0016 != 0 )
1177    {
1178       // Create 'Source Image Sequence' SeqEntry
1179       SeqEntry *s = new SeqEntry (
1180             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x2112) );
1181       SQItem *sqi = new SQItem(1);
1182       // (we assume 'SOP Instance UID' exists too) 
1183       // create 'Referenced SOP Class UID'
1184       ValEntry *e_0008_1150 = new ValEntry(
1185             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1150) );
1186       e_0008_1150->SetValue( e_0008_0016->GetValue());
1187       sqi->AddEntry(e_0008_1150);
1188       
1189       // create 'Referenced SOP Instance UID'
1190       ValEntry *e_0008_0018 = FileInternal->GetValEntry(0x0008, 0x0018);
1191       ValEntry *e_0008_1155 = new ValEntry(
1192             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1155) );
1193       e_0008_1155->SetValue( e_0008_0018->GetValue());
1194       sqi->AddEntry(e_0008_1155);
1195
1196       s->AddSQItem(sqi,1); 
1197       // temporarily replaces any previous 'Source Image Sequence' 
1198       Archive->Push(s);
1199  
1200       // 'Image Type' (The written image is no longer an 'ORIGINAL' one)
1201       ValEntry *e_0008_0008 = CopyValEntry(0x0008,0x0008);
1202       e_0008_0008->SetValue("DERIVED\\PRIMARY");
1203       Archive->Push(e_0008_0008);
1204    } 
1205    else
1206    {
1207       // There was no 'SOP Class UID'.
1208       // the source image was NOT a true Dicom one.
1209       // We consider the image is a 'Secondary Capture' one
1210       // SOP Class UID
1211       e_0008_0016  =  new ValEntry( 
1212             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0016) );
1213       // [Secondary Capture Image Storage]
1214       e_0008_0016 ->SetValue("1.2.840.10008.5.1.4.1.1.7"); 
1215       Archive->Push(e_0008_0016); 
1216    }
1217
1218 // ---- The user will never have to take any action on the following ----.
1219
1220    // new value for 'SOP Instance UID'
1221    ValEntry *e_0008_0018 = new ValEntry(
1222          Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0018) );
1223    e_0008_0018->SetValue( Util::CreateUniqueUID() );
1224    Archive->Push(e_0008_0018);
1225
1226    // Instance Creation Date
1227    ValEntry *e_0008_0012 = CopyValEntry(0x0008,0x0012);
1228    std::string date = Util::GetCurrentDate();
1229    e_0008_0012->SetValue(date.c_str());
1230    Archive->Push(e_0008_0012);
1231  
1232    // Instance Creation Time
1233    ValEntry *e_0008_0013 = CopyValEntry(0x0008,0x0013);
1234    std::string time = Util::GetCurrentTime();
1235    e_0008_0013->SetValue(time.c_str());
1236    Archive->Push(e_0008_0013);
1237
1238 // ----- Add Mandatory Entries if missing ---
1239
1240 // Entries whose type is 1 are mandatory, with a mandatory value
1241 // Entries whose type is 1c are mandatory-inside-a-Sequence
1242 // Entries whose type is 2 are mandatory, with a optional value
1243 // Entries whose type is 2c are mandatory-inside-a-Sequence
1244 // Entries whose type is 3 are optional
1245
1246    // 'Serie Instance UID'
1247    // Keep the value if exists
1248    // The user is allowed to create his own Series, 
1249    // keeping the same 'Serie Instance UID' for various images
1250    // The user shouldn't add any image to a 'Manufacturer Serie'
1251    // but there is no way no to allowed him to do that 
1252    ValEntry *e_0020_000e = FileInternal->GetValEntry(0x0020, 0x000e);
1253    if ( !e_0020_000e )
1254    {
1255       e_0020_000e = new ValEntry(
1256            Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0020, 0x000e) );
1257       e_0020_000e->SetValue(Util::CreateUniqueUID() );
1258       Archive->Push(e_0020_000e);
1259    } 
1260
1261    // 'Study Instance UID'
1262    // Keep the value if exists
1263    // The user is allowed to create his own Study, 
1264    //          keeping the same 'Study Instance UID' for various images
1265    // The user may add images to a 'Manufacturer Study',
1266    //          adding new series to an already existing Study 
1267    ValEntry *e_0020_000d = FileInternal->GetValEntry(0x0020, 0x000d);
1268    if ( !e_0020_000d )
1269    {
1270       e_0020_000d = new ValEntry(
1271             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0020, 0x000d) );
1272       e_0020_000d->SetValue(Util::CreateUniqueUID() );
1273       Archive->Push(e_0020_000d);
1274    }
1275
1276    // Modality : if missing we set it to 'OTher'
1277    ValEntry *e_0008_0060 = FileInternal->GetValEntry(0x0008, 0x0060);
1278    if ( !e_0008_0060 )
1279    {
1280       e_0008_0060 = new ValEntry(
1281             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0060) );
1282       e_0008_0060->SetValue("OT");
1283       Archive->Push(e_0008_0060);
1284    } 
1285
1286    // Manufacturer : if missing we set it to 'GDCM Factory'
1287    ValEntry *e_0008_0070 = FileInternal->GetValEntry(0x0008, 0x0070);
1288    if ( !e_0008_0070 )
1289    {
1290       e_0008_0070 = new ValEntry(
1291             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0070) );
1292       e_0008_0070->SetValue("GDCM Factory");
1293       Archive->Push(e_0008_0070);
1294    } 
1295
1296    // Institution Name : if missing we set it to 'GDCM Hospital'
1297    ValEntry *e_0008_0080 = FileInternal->GetValEntry(0x0008, 0x0080);
1298    if ( !e_0008_0080 )
1299    {
1300       e_0008_0080 = new ValEntry(
1301             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0080) );
1302       e_0008_0080->SetValue("GDCM Hospital");
1303       Archive->Push(e_0008_0080);
1304    } 
1305
1306    // Patient's Name : if missing, we set it to 'GDCM^Patient'
1307    ValEntry *e_0010_0010 = FileInternal->GetValEntry(0x0010, 0x0010);
1308    if ( !e_0010_0010 )
1309    {
1310       e_0010_0010 = new ValEntry(
1311             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0010, 0x0010) );
1312       e_0010_0010->SetValue("GDCM^Patient");
1313       Archive->Push(e_0010_0010);
1314    } 
1315
1316    // Patient's Birth Date : 'type 2' entry -> must exist, value not mandatory
1317    ValEntry *e_0010_0030 = FileInternal->GetValEntry(0x0010, 0x0030);
1318    if ( !e_0010_0030 )
1319    {
1320       e_0010_0030 = new ValEntry(
1321             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0010, 0x0030) );
1322       e_0010_0030->SetValue("");
1323       Archive->Push(e_0010_0030);
1324    }
1325
1326    // Patient's Sex :'type 2' entry -> must exist, value not mandatory
1327    ValEntry *e_0010_0040 = FileInternal->GetValEntry(0x0010, 0x0040);
1328    if ( !e_0010_0040 )
1329    {
1330       e_0010_0040 = new ValEntry(
1331             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0010, 0x0040) );
1332       e_0010_0040->SetValue("");
1333       Archive->Push(e_0010_0040);
1334    }
1335
1336    // Referring Physician's Name :'type 2' entry -> must exist, value not mandatory
1337    ValEntry *e_0008_0090 = FileInternal->GetValEntry(0x0008, 0x0090);
1338    if ( !e_0008_0090 )
1339    {
1340       e_0008_0090 = new ValEntry(
1341             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0090) );
1342       e_0008_0090->SetValue("");
1343       Archive->Push(e_0008_0090);
1344    }
1345  
1346    // Remove some inconstencies (probably some more will be added)
1347
1348    // if (0028 0008)Number of Frames exists
1349    //    Push out (0020 0052),Frame of Reference UID
1350    //    (only meaningfull within a Serie)
1351    ValEntry *e_0028_0008 = FileInternal->GetValEntry(0x0028, 0x0008);
1352    if ( !e_0028_0008 )
1353    {
1354       Archive->Push(0x0020, 0X0052);
1355    }
1356
1357  
1358 /**
1359  * \brief Restore in the File the initial group 0002
1360  */
1361 void FileHelper::RestoreWriteMandatory()
1362 {
1363    // group 0002 may be pushed out for ACR-NEMA writting purposes 
1364    Archive->Restore(0x0002,0x0000);
1365    Archive->Restore(0x0002,0x0001);
1366    Archive->Restore(0x0002,0x0002);
1367    Archive->Restore(0x0002,0x0003);
1368    Archive->Restore(0x0002,0x0012);
1369    Archive->Restore(0x0002,0x0013);
1370    Archive->Restore(0x0002,0x0016);
1371    Archive->Restore(0x0002,0x0100);
1372    Archive->Restore(0x0002,0x0102);
1373
1374    Archive->Restore(0x0008,0x0012);
1375    Archive->Restore(0x0008,0x0013);
1376    Archive->Restore(0x0008,0x0016);
1377    Archive->Restore(0x0008,0x0018);
1378    Archive->Restore(0x0008,0x0060);
1379    Archive->Restore(0x0008,0x0070);
1380    Archive->Restore(0x0008,0x0080);
1381    Archive->Restore(0x0008,0x0090);
1382    Archive->Restore(0x0008,0x2112);
1383
1384    Archive->Restore(0x0010,0x0010);
1385    Archive->Restore(0x0010,0x0030);
1386    Archive->Restore(0x0010,0x0040);
1387
1388    Archive->Restore(0x0020,0x000d);
1389    Archive->Restore(0x0020,0x000e);
1390
1391 }
1392
1393 //-----------------------------------------------------------------------------
1394 // Private
1395 /**
1396  * \brief Factorization for various forms of constructors.
1397  */
1398 void FileHelper::Initialize()
1399 {
1400    WriteMode = WMODE_RAW;
1401    WriteType = ExplicitVR;
1402
1403    PixelReadConverter  = new PixelReadConvert;
1404    PixelWriteConverter = new PixelWriteConvert;
1405    Archive = new DocEntryArchive( FileInternal );
1406
1407    if ( FileInternal->IsReadable() )
1408    {
1409       PixelReadConverter->GrabInformationsFromFile( FileInternal );
1410    }
1411 }
1412
1413 /**
1414  * \brief Reads/[decompresses] the pixels, 
1415  *        *without* making RGB from Palette Colors 
1416  * @return the pixels area, whatever its type 
1417  *         (uint8_t is just for prototyping : feel free to Cast it) 
1418  */ 
1419 uint8_t *FileHelper::GetRaw()
1420 {
1421    uint8_t *raw = PixelReadConverter->GetRaw();
1422    if ( ! raw )
1423    {
1424       // The Raw image migth not be loaded yet:
1425       std::ifstream *fp = FileInternal->OpenFile();
1426       PixelReadConverter->ReadAndDecompressPixelData( fp );
1427       if(fp) 
1428          FileInternal->CloseFile();
1429
1430       raw = PixelReadConverter->GetRaw();
1431       if ( ! raw )
1432       {
1433          gdcmWarningMacro( "Read/decompress of pixel data apparently went wrong.");
1434          return 0;
1435       }
1436    }
1437    return raw;
1438 }
1439
1440 //-----------------------------------------------------------------------------
1441 /**
1442  * \brief   Prints the common part of ValEntry, BinEntry, SeqEntry
1443  * @param   os ostream we want to print in
1444  * @param indent (unused)
1445  */
1446 void FileHelper::Print(std::ostream &os, std::string const &)
1447 {
1448    FileInternal->SetPrintLevel(PrintLevel);
1449    FileInternal->Print(os);
1450
1451    PixelReadConverter->SetPrintLevel(PrintLevel);
1452    PixelReadConverter->Print(os);
1453 }
1454
1455 //-----------------------------------------------------------------------------
1456 } // end namespace gdcm