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