]> Creatis software - gdcm.git/blob - src/gdcmFileHelper.cxx
FIX possible troubles when checking
[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/19 15:31:21 $
8   Version:   $Revision: 1.39 $
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          gdcmWarningMacro( "numberBitsAllocated changed from " 
699                           << numberBitsAllocated << " to 16 " 
700                           << " for consistency purpose" );
701          numberBitsAllocated = 16;
702       }
703
704       size_t decSize = FileInternal->GetXSize()
705                      * FileInternal->GetYSize() 
706                      * FileInternal->GetZSize()
707                      * FileInternal->GetSamplesPerPixel()
708                      * ( numberBitsAllocated / 8 );
709       size_t rgbSize = decSize;
710       if( FileInternal->HasLUT() )
711          rgbSize = decSize * 3;
712
713       switch(WriteMode)
714       {
715          case WMODE_RAW :
716             if( decSize!=PixelWriteConverter->GetUserDataSize() )
717             {
718                gdcmWarningMacro( "Data size (Raw) is incorrect. Should be " 
719                            << decSize << " / Found :" 
720                            << PixelWriteConverter->GetUserDataSize() );
721                return false;
722             }
723             break;
724          case WMODE_RGB :
725             if( rgbSize!=PixelWriteConverter->GetUserDataSize() )
726             {
727                gdcmWarningMacro( "Data size (RGB) is incorrect. Should be " 
728                           << decSize << " / Found " 
729                           << PixelWriteConverter->GetUserDataSize() );
730                return false;
731             }
732             break;
733       }
734    }   
735    return true;
736 }
737
738 /**
739  * \brief Updates the File to write RAW data (as opposed to RGB data)
740  *       (modifies, when necessary, photochromatic interpretation, 
741  *       bits allocated, Pixels element VR)
742  */ 
743 void FileHelper::SetWriteToRaw()
744 {
745    if( FileInternal->GetNumberOfScalarComponents() == 3 
746     && !FileInternal->HasLUT())
747    {
748       SetWriteToRGB();
749    } 
750    else
751    {
752       ValEntry *photInt = CopyValEntry(0x0028,0x0004);
753       if(FileInternal->HasLUT())
754       {
755          photInt->SetValue("PALETTE COLOR ");
756       }
757       else
758       {
759          photInt->SetValue("MONOCHROME2 ");
760       }
761
762       PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
763                                        PixelReadConverter->GetRawSize());
764
765       std::string vr = "OB";
766       if( FileInternal->GetBitsAllocated()>8 )
767          vr = "OW";
768       if( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files 
769          vr = "OB";
770       BinEntry *pixel = 
771          CopyBinEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
772       pixel->SetValue(GDCM_BINLOADED);
773       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
774       pixel->SetLength(PixelWriteConverter->GetDataSize());
775
776       Archive->Push(photInt);
777       Archive->Push(pixel);
778    }
779 }
780
781 /**
782  * \brief Updates the File to write RGB data (as opposed to RAW data)
783  *       (modifies, when necessary, photochromatic interpretation, 
784  *       samples per pixel, Planar configuration, 
785  *       bits allocated, bits stored, high bit -ACR 24 bits-
786  *       Pixels element VR, pushes out the LUT, )
787  */ 
788 void FileHelper::SetWriteToRGB()
789 {
790    if(FileInternal->GetNumberOfScalarComponents()==3)
791    {
792       PixelReadConverter->BuildRGBImage();
793       
794       ValEntry *spp = CopyValEntry(0x0028,0x0002);
795       spp->SetValue("3 ");
796
797       ValEntry *planConfig = CopyValEntry(0x0028,0x0006);
798       planConfig->SetValue("0 ");
799
800       ValEntry *photInt = CopyValEntry(0x0028,0x0004);
801       photInt->SetValue("RGB ");
802
803       if(PixelReadConverter->GetRGB())
804       {
805          PixelWriteConverter->SetReadData(PixelReadConverter->GetRGB(),
806                                           PixelReadConverter->GetRGBSize());
807       }
808       else // Raw data
809       {
810          PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
811                                           PixelReadConverter->GetRawSize());
812       }
813
814       std::string vr = "OB";
815       if( FileInternal->GetBitsAllocated()>8 )
816          vr = "OW";
817       if( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files 
818          vr = "OB";
819       BinEntry *pixel = 
820          CopyBinEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
821       pixel->SetValue(GDCM_BINLOADED);
822       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
823       pixel->SetLength(PixelWriteConverter->GetDataSize());
824
825       Archive->Push(spp);
826       Archive->Push(planConfig);
827       Archive->Push(photInt);
828       Archive->Push(pixel);
829
830       // Remove any LUT
831       Archive->Push(0x0028,0x1101);
832       Archive->Push(0x0028,0x1102);
833       Archive->Push(0x0028,0x1103);
834       Archive->Push(0x0028,0x1201);
835       Archive->Push(0x0028,0x1202);
836       Archive->Push(0x0028,0x1203);
837
838       // For old '24 Bits' ACR-NEMA
839       // Thus, we have a RGB image and the bits allocated = 24 and 
840       // samples per pixels = 1 (in the read file)
841       if(FileInternal->GetBitsAllocated()==24) 
842       {
843          ValEntry *bitsAlloc = CopyValEntry(0x0028,0x0100);
844          bitsAlloc->SetValue("8 ");
845
846          ValEntry *bitsStored = CopyValEntry(0x0028,0x0101);
847          bitsStored->SetValue("8 ");
848
849          ValEntry *highBit = CopyValEntry(0x0028,0x0102);
850          highBit->SetValue("7 ");
851
852          Archive->Push(bitsAlloc);
853          Archive->Push(bitsStored);
854          Archive->Push(highBit);
855       }
856    }
857    else
858    {
859       SetWriteToRaw();
860    }
861 }
862
863 /**
864  * \brief Restore the File write mode  
865  */ 
866 void FileHelper::RestoreWrite()
867 {
868    Archive->Restore(0x0028,0x0002);
869    Archive->Restore(0x0028,0x0004);
870    Archive->Restore(0x0028,0x0006);
871    Archive->Restore(GetFile()->GetGrPixel(),GetFile()->GetNumPixel());
872
873    // For old ACR-NEMA (24 bits problem)
874    Archive->Restore(0x0028,0x0100);
875    Archive->Restore(0x0028,0x0101);
876    Archive->Restore(0x0028,0x0102);
877
878    // For the LUT
879    Archive->Restore(0x0028,0x1101);
880    Archive->Restore(0x0028,0x1102);
881    Archive->Restore(0x0028,0x1103);
882    Archive->Restore(0x0028,0x1201);
883    Archive->Restore(0x0028,0x1202);
884    Archive->Restore(0x0028,0x1203);
885
886    // group 0002 may be pushed out for ACR-NEMA writting purposes 
887    Archive->Restore(0x0002,0x0000);
888    Archive->Restore(0x0002,0x0001);
889    Archive->Restore(0x0002,0x0002);
890    Archive->Restore(0x0002,0x0003);
891    Archive->Restore(0x0002,0x0010);
892    Archive->Restore(0x0002,0x0012);
893    Archive->Restore(0x0002,0x0013);
894    Archive->Restore(0x0002,0x0016);
895    Archive->Restore(0x0002,0x0100);
896    Archive->Restore(0x0002,0x0102);
897 }
898
899 /**
900  * \brief Pushes out the whole group 0002
901  *        FIXME : better, set a flag to tell the writer not to write it ...
902  *        FIXME : method should probably have an other name !
903  *                SetWriteFileTypeToACR is NOT opposed to 
904  *                SetWriteFileTypeToExplicitVR and SetWriteFileTypeToImplicitVR
905  */ 
906 void FileHelper::SetWriteFileTypeToACR()
907 {
908    Archive->Push(0x0002,0x0000);
909    Archive->Push(0x0002,0x0001);
910    Archive->Push(0x0002,0x0002);
911    Archive->Push(0x0002,0x0003);
912    Archive->Push(0x0002,0x0010);
913    Archive->Push(0x0002,0x0012);
914    Archive->Push(0x0002,0x0013);
915    Archive->Push(0x0002,0x0016);
916    Archive->Push(0x0002,0x0100);
917    Archive->Push(0x0002,0x0102);
918 }
919
920 /**
921  * \brief Sets in the File the TransferSyntax to 'Explicit VR Little Endian"   
922  */ 
923 void FileHelper::SetWriteFileTypeToExplicitVR()
924 {
925    std::string ts = Util::DicomString( 
926       Global::GetTS()->GetSpecialTransferSyntax(TS::ExplicitVRLittleEndian) );
927
928    ValEntry *tss = CopyValEntry(0x0002,0x0010);
929    tss->SetValue(ts);
930
931    Archive->Push(tss);
932 }
933
934 /**
935  * \brief Sets in the File the TransferSyntax to 'Implicit VR Little Endian"   
936  */ 
937 void FileHelper::SetWriteFileTypeToImplicitVR()
938 {
939    std::string ts = Util::DicomString(
940       Global::GetTS()->GetSpecialTransferSyntax(TS::ImplicitVRLittleEndian) );
941
942    ValEntry *tss = CopyValEntry(0x0002,0x0010);
943    tss->SetValue(ts);
944
945    Archive->Push(tss);
946 }
947
948
949 /**
950  * \brief Restore in the File the initial group 0002
951  */ 
952 void FileHelper::RestoreWriteFileType()
953 {
954 }
955
956 /**
957  * \brief Set the Write not to Libido format
958  */ 
959 void FileHelper::SetWriteToLibido()
960 {
961    ValEntry *oldRow = dynamic_cast<ValEntry *>
962                 (FileInternal->GetDocEntry(0x0028, 0x0010));
963    ValEntry *oldCol = dynamic_cast<ValEntry *>
964                 (FileInternal->GetDocEntry(0x0028, 0x0011));
965    
966    if( oldRow && oldCol )
967    {
968       std::string rows, columns; 
969
970       ValEntry *newRow=new ValEntry(oldRow->GetDictEntry());
971       ValEntry *newCol=new ValEntry(oldCol->GetDictEntry());
972
973       newRow->Copy(oldCol);
974       newCol->Copy(oldRow);
975
976       newRow->SetValue(oldCol->GetValue());
977       newCol->SetValue(oldRow->GetValue());
978
979       Archive->Push(newRow);
980       Archive->Push(newCol);
981    }
982
983    ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
984    libidoCode->SetValue("ACRNEMA_LIBIDO_1.1");
985    Archive->Push(libidoCode);
986 }
987
988 /**
989  * \brief Set the Write not to No Libido format
990  */ 
991 void FileHelper::SetWriteToNoLibido()
992 {
993    ValEntry *recCode = dynamic_cast<ValEntry *>
994                 (FileInternal->GetDocEntry(0x0008,0x0010));
995    if( recCode )
996    {
997       if( recCode->GetValue() == "ACRNEMA_LIBIDO_1.1" )
998       {
999          ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
1000          libidoCode->SetValue("");
1001          Archive->Push(libidoCode);
1002       }
1003    }
1004 }
1005
1006 /**
1007  * \brief Restore the Write format
1008  */ 
1009 void FileHelper::RestoreWriteOfLibido()
1010 {
1011    Archive->Restore(0x0028,0x0010);
1012    Archive->Restore(0x0028,0x0011);
1013    Archive->Restore(0x0008,0x0010);
1014
1015    // Restore 'LibIDO-special' entries, if any
1016    Archive->Restore(0x0028,0x0015);
1017    Archive->Restore(0x0028,0x0016);
1018    Archive->Restore(0x0028,0x0017);
1019    Archive->Restore(0x0028,0x00199);
1020 }
1021
1022 /**
1023  * \brief Duplicates a ValEntry or creates it.
1024  * @param   group   Group number of the Entry 
1025  * @param   elem  Element number of the Entry
1026  * \return  pointer to the new Val Entry (NULL when creation failed).          
1027  */ 
1028 ValEntry *FileHelper::CopyValEntry(uint16_t group, uint16_t elem)
1029 {
1030    DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
1031    ValEntry *newE;
1032
1033    if( oldE )
1034    {
1035       newE = new ValEntry(oldE->GetDictEntry());
1036       newE->Copy(oldE);
1037    }
1038    else
1039    {
1040       newE = GetFile()->NewValEntry(group, elem);
1041    }
1042
1043    return newE;
1044 }
1045
1046 /**
1047  * \brief   Duplicates a BinEntry or creates it.
1048  * @param   group   Group number of the Entry 
1049  * @param   elem  Element number of the Entry
1050  * @param   vr  Value Representation of the Entry
1051  *          FIXME : what is it used for?
1052  * \return  pointer to the new Bin Entry (NULL when creation failed).
1053  */ 
1054 BinEntry *FileHelper::CopyBinEntry(uint16_t group, uint16_t elem,
1055                                    const std::string &vr)
1056 {
1057    DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
1058    BinEntry *newE;
1059
1060    if( oldE ) 
1061       if( oldE->GetVR()!=vr )
1062          oldE = NULL;
1063
1064    if( oldE )
1065    {
1066       newE = new BinEntry(oldE->GetDictEntry());
1067       newE->Copy(oldE);
1068    }
1069    else
1070    {
1071       newE = GetFile()->NewBinEntry(group, elem, vr);
1072    }
1073
1074    return newE;
1075 }
1076
1077 /**
1078  * \brief   This method is called automatically, just before writting
1079  *         in order to produce a 'True Dicom V3' image
1080  *         We cannot know *how* the user made the File (reading an old ACR-NEMA
1081  *         file or a not very clean DICOM file ...) 
1082  *          
1083  *          Just before writting :
1084  *             - we check the Entries
1085  *             - we create the mandatory entries if they are missing
1086  *             - we modify the values if necessary
1087  *             - we push the sensitive entries to the Archive
1088  *          The writing process will restore the entries as they where before 
1089  *          entering FileHelper::CheckMandatoryElements, so the user will always
1090  *          see the entries just as he left them.
1091  * 
1092  * \todo : - warn the user if we had to add some entries :
1093  *         even if a mandatory entry is missing, we add it, with a default value
1094  *         (we don't want to give up the writting process if user forgot to
1095  *         specify Lena's Patient ID, for instance ...)
1096  *         - read the whole PS 3.3 Part of DICOM  (890 pages)
1097  *         and write a *full* checker (probably one method per Modality ...)
1098  *         Any contribution is welcome. 
1099  *         - write a user callable full checker, to allow post reading
1100  *         and/or pre writting image consistency check.           
1101  */ 
1102  
1103 void FileHelper::CheckMandatoryElements()
1104 {
1105
1106    // just to remember : 'official' 0002 group
1107
1108    //0002 0000 UL 1 Meta Group Length
1109    //0002 0001 OB 1 File Meta Information Version
1110    //0002 0002 UI 1 Media Stored SOP Class UID
1111    //0002 0003 UI 1 Media Stored SOP Instance UID
1112    //0002 0010 UI 1 Transfer Syntax UID
1113    //0002 0012 UI 1 Implementation Class UID
1114    //0002 0013 SH 1 Implementation Version Name
1115    //0002 0016 AE 1 Source Application Entity Title
1116    //0002 0100 UI 1 Private Information Creator
1117    //0002 0102 OB 1 Private Information
1118   
1119    // Create them if not found
1120    // Always modify the value
1121    // Push the entries to the archive.
1122    ValEntry *e_0002_0000 = CopyValEntry(0x0002,0x0000);
1123       e_0002_0000->SetValue("0"); // for the moment
1124       Archive->Push(e_0002_0000);
1125   
1126    BinEntry *e_0002_0001 = CopyBinEntry(0x0002,0x0001, "OB");
1127       e_0002_0001->SetBinArea((uint8_t*)Util::GetFileMetaInformationVersion(),
1128                                false);
1129       e_0002_0001->SetLength(2);
1130       Archive->Push(e_0002_0001);
1131
1132    // 'Media Stored SOP Class UID' 
1133    ValEntry *e_0002_0002 = CopyValEntry(0x0002,0x0002);
1134       // [Secondary Capture Image Storage]
1135       e_0002_0002->SetValue("1.2.840.10008.5.1.4.1.1.7"); 
1136       Archive->Push(e_0002_0002);
1137  
1138    // 'Media Stored SOP Instance UID'   
1139    ValEntry *e_0002_0003 = CopyValEntry(0x0002,0x0003);
1140       e_0002_0003->SetValue(Util::CreateUniqueUID());
1141       Archive->Push(e_0002_0003); 
1142
1143    // 'Implementation Class UID'
1144    ValEntry *e_0002_0012 = CopyValEntry(0x0002,0x0012);
1145       e_0002_0012->SetValue(Util::CreateUniqueUID());
1146       Archive->Push(e_0002_0012); 
1147
1148    // 'Implementation Version Name'
1149    ValEntry *e_0002_0013 = CopyValEntry(0x0002,0x0013);
1150       e_0002_0013->SetValue("GDCM 1.0");
1151       Archive->Push(e_0002_0013);
1152
1153    //'Source Application Entity Title' Not Mandatory
1154    //ValEntry *e_0002_0016 = CopyValEntry(0x0002,0x0016);
1155    //   e_0002_0016->SetValue("1.2.840.10008.5.1.4.1.1.7");
1156    //   Archive->Push(e_0002_0016);
1157
1158    // Push out 'LibIDO-special' entries, if any
1159    Archive->Push(0x0028,0x0015);
1160    Archive->Push(0x0028,0x0016);
1161    Archive->Push(0x0028,0x0017);
1162    Archive->Push(0x0028,0x00199);
1163
1164    // Deal with the pb of (Bits Stored = 12)
1165    // - we're gonna write the image as Bits Stored = 16
1166    if ( FileInternal->GetEntryValue(0x0028,0x0100) ==  "12")
1167    {
1168       ValEntry *e_0028_0100 = CopyValEntry(0x0028,0x0100);
1169       e_0028_0100->SetValue("16");
1170       Archive->Push(e_0028_0100);
1171    }
1172
1173    // Check if user wasn't drunk ;-)
1174
1175    std::ostringstream s;
1176    // check 'Bits Allocated' vs decent values
1177    int nbBitsAllocated = FileInternal->GetBitsAllocated();
1178    if ( nbBitsAllocated == 0 || nbBitsAllocated > 32)
1179    {
1180       ValEntry *e_0028_0100 = CopyValEntry(0x0028,0x0100);
1181       e_0028_0100->SetValue("16");
1182       Archive->Push(e_0028_0100); 
1183       gdcmWarningMacro("(0028,0100) changed from "
1184          << nbBitsAllocated << " to 16 for consistency purpose");
1185       nbBitsAllocated = 16; 
1186    }
1187    // check 'Bits Stored' vs 'Bits Allocated'   
1188    int nbBitsStored = FileInternal->GetBitsStored();
1189    if ( nbBitsStored == 0 || nbBitsStored > nbBitsAllocated )
1190    {
1191       s << nbBitsAllocated;
1192       ValEntry *e_0028_0101 = CopyValEntry(0x0028,0x0101);
1193       e_0028_0101->SetValue( s.str() );
1194       Archive->Push(e_0028_0101);
1195       gdcmWarningMacro("(0028,0101) changed from "
1196                        << nbBitsStored << " to " << nbBitsAllocated
1197                        << " for consistency purpose" );
1198       nbBitsStored = nbBitsAllocated; 
1199     }
1200    // check 'Hight Bit Position' vs 'Bits Allocated' and 'Bits Stored'
1201    int highBitPosition = FileInternal->GetHighBitPosition();
1202    if ( highBitPosition == 0 || 
1203         highBitPosition > nbBitsAllocated-1 ||
1204         highBitPosition < nbBitsStored-1  )
1205    {
1206       ValEntry *e_0028_0102 = CopyValEntry(0x0028,0x0102);
1207
1208       s << nbBitsStored - 1; 
1209       e_0028_0102->SetValue( s.str() );
1210       Archive->Push(e_0028_0102);
1211       gdcmWarningMacro("(0028,0102) changed from "
1212                        << highBitPosition << " to " << nbBitsAllocated-1
1213                        << " for consistency purpose");
1214    }
1215   // --- Check UID-related Entries ---
1216
1217    // If 'SOP Class UID' exists ('true DICOM' image)
1218    // we create the 'Source Image Sequence' SeqEntry
1219    // to hold informations about the Source Image
1220
1221    ValEntry *e_0008_0016 = FileInternal->GetValEntry(0x0008, 0x0016);
1222    if ( e_0008_0016 != 0 )
1223    {
1224       // Create 'Source Image Sequence' SeqEntry
1225       SeqEntry *s = new SeqEntry (
1226             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x2112) );
1227       SQItem *sqi = new SQItem(1);
1228       // (we assume 'SOP Instance UID' exists too) 
1229       // create 'Referenced SOP Class UID'
1230       ValEntry *e_0008_1150 = new ValEntry(
1231             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1150) );
1232       e_0008_1150->SetValue( e_0008_0016->GetValue());
1233       sqi->AddEntry(e_0008_1150);
1234       
1235       // create 'Referenced SOP Instance UID'
1236       ValEntry *e_0008_0018 = FileInternal->GetValEntry(0x0008, 0x0018);
1237       ValEntry *e_0008_1155 = new ValEntry(
1238             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1155) );
1239       e_0008_1155->SetValue( e_0008_0018->GetValue());
1240       sqi->AddEntry(e_0008_1155);
1241
1242       s->AddSQItem(sqi,1); 
1243       // temporarily replaces any previous 'Source Image Sequence' 
1244       Archive->Push(s);
1245  
1246       // 'Image Type' (The written image is no longer an 'ORIGINAL' one)
1247       ValEntry *e_0008_0008 = CopyValEntry(0x0008,0x0008);
1248       e_0008_0008->SetValue("DERIVED\\PRIMARY");
1249       Archive->Push(e_0008_0008);
1250    } 
1251    else
1252    {
1253       // There was no 'SOP Class UID'.
1254       // the source image was NOT a true Dicom one.
1255       // We consider the image is a 'Secondary Capture' one
1256       // SOP Class UID
1257       e_0008_0016  =  new ValEntry( 
1258             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0016) );
1259       // [Secondary Capture Image Storage]
1260       e_0008_0016 ->SetValue("1.2.840.10008.5.1.4.1.1.7"); 
1261       Archive->Push(e_0008_0016); 
1262    }
1263
1264 // ---- The user will never have to take any action on the following ----.
1265
1266    // new value for 'SOP Instance UID'
1267    ValEntry *e_0008_0018 = new ValEntry(
1268          Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0018) );
1269    e_0008_0018->SetValue( Util::CreateUniqueUID() );
1270    Archive->Push(e_0008_0018);
1271
1272    // Instance Creation Date
1273    ValEntry *e_0008_0012 = CopyValEntry(0x0008,0x0012);
1274    std::string date = Util::GetCurrentDate();
1275    e_0008_0012->SetValue(date.c_str());
1276    Archive->Push(e_0008_0012);
1277  
1278    // Instance Creation Time
1279    ValEntry *e_0008_0013 = CopyValEntry(0x0008,0x0013);
1280    std::string time = Util::GetCurrentTime();
1281    e_0008_0013->SetValue(time.c_str());
1282    Archive->Push(e_0008_0013);
1283
1284 // ----- Add Mandatory Entries if missing ---
1285
1286 // Entries whose type is 1 are mandatory, with a mandatory value
1287 // Entries whose type is 1c are mandatory-inside-a-Sequence
1288 // Entries whose type is 2 are mandatory, with a optional value
1289 // Entries whose type is 2c are mandatory-inside-a-Sequence
1290 // Entries whose type is 3 are optional
1291
1292    // 'Serie Instance UID'
1293    // Keep the value if exists
1294    // The user is allowed to create his own Series, 
1295    // keeping the same 'Serie Instance UID' for various images
1296    // The user shouldn't add any image to a 'Manufacturer Serie'
1297    // but there is no way no to allowed him to do that 
1298    ValEntry *e_0020_000e = FileInternal->GetValEntry(0x0020, 0x000e);
1299    if ( !e_0020_000e )
1300    {
1301       e_0020_000e = new ValEntry(
1302            Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0020, 0x000e) );
1303       e_0020_000e->SetValue(Util::CreateUniqueUID() );
1304       Archive->Push(e_0020_000e);
1305    } 
1306
1307    // 'Study Instance UID'
1308    // Keep the value if exists
1309    // The user is allowed to create his own Study, 
1310    //          keeping the same 'Study Instance UID' for various images
1311    // The user may add images to a 'Manufacturer Study',
1312    //          adding new series to an already existing Study 
1313    ValEntry *e_0020_000d = FileInternal->GetValEntry(0x0020, 0x000d);
1314    if ( !e_0020_000d )
1315    {
1316       e_0020_000d = new ValEntry(
1317             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0020, 0x000d) );
1318       e_0020_000d->SetValue(Util::CreateUniqueUID() );
1319       Archive->Push(e_0020_000d);
1320    }
1321
1322    // Modality : if missing we set it to 'OTher'
1323    ValEntry *e_0008_0060 = FileInternal->GetValEntry(0x0008, 0x0060);
1324    if ( !e_0008_0060 )
1325    {
1326       e_0008_0060 = new ValEntry(
1327             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0060) );
1328       e_0008_0060->SetValue("OT");
1329       Archive->Push(e_0008_0060);
1330    } 
1331
1332    // Manufacturer : if missing we set it to 'GDCM Factory'
1333    ValEntry *e_0008_0070 = FileInternal->GetValEntry(0x0008, 0x0070);
1334    if ( !e_0008_0070 )
1335    {
1336       e_0008_0070 = new ValEntry(
1337             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0070) );
1338       e_0008_0070->SetValue("GDCM Factory");
1339       Archive->Push(e_0008_0070);
1340    } 
1341
1342    // Institution Name : if missing we set it to 'GDCM Hospital'
1343    ValEntry *e_0008_0080 = FileInternal->GetValEntry(0x0008, 0x0080);
1344    if ( !e_0008_0080 )
1345    {
1346       e_0008_0080 = new ValEntry(
1347             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0080) );
1348       e_0008_0080->SetValue("GDCM Hospital");
1349       Archive->Push(e_0008_0080);
1350    } 
1351
1352    // Patient's Name : if missing, we set it to 'GDCM^Patient'
1353    ValEntry *e_0010_0010 = FileInternal->GetValEntry(0x0010, 0x0010);
1354    if ( !e_0010_0010 )
1355    {
1356       e_0010_0010 = new ValEntry(
1357             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0010, 0x0010) );
1358       e_0010_0010->SetValue("GDCM^Patient");
1359       Archive->Push(e_0010_0010);
1360    } 
1361
1362    // Patient's Birth Date : 'type 2' entry -> must exist, value not mandatory
1363    ValEntry *e_0010_0030 = FileInternal->GetValEntry(0x0010, 0x0030);
1364    if ( !e_0010_0030 )
1365    {
1366       e_0010_0030 = new ValEntry(
1367             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0010, 0x0030) );
1368       e_0010_0030->SetValue("");
1369       Archive->Push(e_0010_0030);
1370    }
1371
1372    // Patient's Sex :'type 2' entry -> must exist, value not mandatory
1373    ValEntry *e_0010_0040 = FileInternal->GetValEntry(0x0010, 0x0040);
1374    if ( !e_0010_0040 )
1375    {
1376       e_0010_0040 = new ValEntry(
1377             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0010, 0x0040) );
1378       e_0010_0040->SetValue("");
1379       Archive->Push(e_0010_0040);
1380    }
1381
1382    // Referring Physician's Name :'type 2' entry -> must exist, value not mandatory
1383    ValEntry *e_0008_0090 = FileInternal->GetValEntry(0x0008, 0x0090);
1384    if ( !e_0008_0090 )
1385    {
1386       e_0008_0090 = new ValEntry(
1387             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0090) );
1388       e_0008_0090->SetValue("");
1389       Archive->Push(e_0008_0090);
1390    }
1391  
1392    // Remove some inconstencies (probably some more will be added)
1393
1394    // if (0028 0008)Number of Frames exists
1395    //    Push out (0020 0052),Frame of Reference UID
1396    //    (only meaningfull within a Serie)
1397    ValEntry *e_0028_0008 = FileInternal->GetValEntry(0x0028, 0x0008);
1398    if ( !e_0028_0008 )
1399    {
1400       Archive->Push(0x0020, 0X0052);
1401    }
1402
1403  
1404 /**
1405  * \brief Restore in the File the initial group 0002
1406  */
1407 void FileHelper::RestoreWriteMandatory()
1408 {
1409    // group 0002 may be pushed out for ACR-NEMA writting purposes 
1410    Archive->Restore(0x0002,0x0000);
1411    Archive->Restore(0x0002,0x0001);
1412    Archive->Restore(0x0002,0x0002);
1413    Archive->Restore(0x0002,0x0003);
1414    Archive->Restore(0x0002,0x0012);
1415    Archive->Restore(0x0002,0x0013);
1416    Archive->Restore(0x0002,0x0016);
1417    Archive->Restore(0x0002,0x0100);
1418    Archive->Restore(0x0002,0x0102);
1419
1420    Archive->Restore(0x0008,0x0012);
1421    Archive->Restore(0x0008,0x0013);
1422    Archive->Restore(0x0008,0x0016);
1423    Archive->Restore(0x0008,0x0018);
1424    Archive->Restore(0x0008,0x0060);
1425    Archive->Restore(0x0008,0x0070);
1426    Archive->Restore(0x0008,0x0080);
1427    Archive->Restore(0x0008,0x0090);
1428    Archive->Restore(0x0008,0x2112);
1429
1430    Archive->Restore(0x0010,0x0010);
1431    Archive->Restore(0x0010,0x0030);
1432    Archive->Restore(0x0010,0x0040);
1433
1434    Archive->Restore(0x0020,0x000d);
1435    Archive->Restore(0x0020,0x000e);
1436
1437 }
1438
1439 //-----------------------------------------------------------------------------
1440 // Private
1441 /**
1442  * \brief Factorization for various forms of constructors.
1443  */
1444 void FileHelper::Initialize()
1445 {
1446    WriteMode = WMODE_RAW;
1447    WriteType = ExplicitVR;
1448
1449    PixelReadConverter  = new PixelReadConvert;
1450    PixelWriteConverter = new PixelWriteConvert;
1451    Archive = new DocEntryArchive( FileInternal );
1452
1453    if ( FileInternal->IsReadable() )
1454    {
1455       PixelReadConverter->GrabInformationsFromFile( FileInternal );
1456    }
1457 }
1458
1459 /**
1460  * \brief Reads/[decompresses] the pixels, 
1461  *        *without* making RGB from Palette Colors 
1462  * @return the pixels area, whatever its type 
1463  *         (uint8_t is just for prototyping : feel free to Cast it) 
1464  */ 
1465 uint8_t *FileHelper::GetRaw()
1466 {
1467    uint8_t *raw = PixelReadConverter->GetRaw();
1468    if ( ! raw )
1469    {
1470       // The Raw image migth not be loaded yet:
1471       std::ifstream *fp = FileInternal->OpenFile();
1472       PixelReadConverter->ReadAndDecompressPixelData( fp );
1473       if(fp) 
1474          FileInternal->CloseFile();
1475
1476       raw = PixelReadConverter->GetRaw();
1477       if ( ! raw )
1478       {
1479          gdcmWarningMacro( "Read/decompress of pixel data apparently went wrong.");
1480          return 0;
1481       }
1482    }
1483    return raw;
1484 }
1485
1486 //-----------------------------------------------------------------------------
1487 /**
1488  * \brief   Prints the common part of ValEntry, BinEntry, SeqEntry
1489  * @param   os ostream we want to print in
1490  * @param indent (unused)
1491  */
1492 void FileHelper::Print(std::ostream &os, std::string const &)
1493 {
1494    FileInternal->SetPrintLevel(PrintLevel);
1495    FileInternal->Print(os);
1496
1497    PixelReadConverter->SetPrintLevel(PrintLevel);
1498    PixelReadConverter->Print(os);
1499 }
1500
1501 //-----------------------------------------------------------------------------
1502 } // end namespace gdcm