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