]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
According to Benoit's suggestion, and without any objection from anybody
[gdcm.git] / src / gdcmFile.cxx
1   /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmFile.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/01/08 15:03:59 $
7   Version:   $Revision: 1.187 $
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 "gdcmFile.h"
20 #include "gdcmDocument.h"
21 #include "gdcmDebug.h"
22 #include "gdcmUtil.h"
23 #include "gdcmBinEntry.h"
24 #include "gdcmHeader.h"
25 #include "gdcmPixelReadConvert.h"
26 #include "gdcmPixelWriteConvert.h"
27 #include "gdcmDocEntryArchive.h"
28
29 #include <fstream>
30
31 namespace gdcm 
32 {
33 typedef std::pair<TagDocEntryHT::iterator,TagDocEntryHT::iterator> IterHT;
34
35 //-------------------------------------------------------------------------
36 // Constructor / Destructor
37 /**
38  * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
39  *        file (Header only deals with the ... header)
40  *        Opens (in read only and when possible) an existing file and checks
41  *        for DICOM compliance. Returns NULL on failure.
42  *        It will be up to the user to load the pixels into memory
43  *        (see GetImageData, GetImageDataRaw)
44  * \note  the in-memory representation of all available tags found in
45  *        the DICOM header is post-poned to first header information access.
46  *        This avoid a double parsing of public part of the header when
47  *        one sets an a posteriori shadow dictionary (efficiency can be
48  *        seen as a side effect).   
49  */
50 File::File( )
51 {
52    HeaderInternal = new Header( );
53    SelfHeader = true;
54    Initialise();
55 }
56
57 /**
58  * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
59  *        file (Header only deals with the ... header)
60  *        Opens (in read only and when possible) an existing file and checks
61  *        for DICOM compliance. Returns NULL on failure.
62  *        It will be up to the user to load the pixels into memory
63  *        (see GetImageData, GetImageDataRaw)
64  * \note  the in-memory representation of all available tags found in
65  *        the DICOM header is post-poned to first header information access.
66  *        This avoid a double parsing of public part of the header when
67  *        user sets an a posteriori shadow dictionary (efficiency can be
68  *        seen as a side effect).   
69  * @param header already built Header
70  */
71 File::File(Header *header)
72 {
73    HeaderInternal = header;
74    SelfHeader = false;
75    Initialise();
76 }
77
78 /**
79  * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
80  *        file (Header only deals with the ... header)
81  *        Opens (in read only and when possible) an existing file and checks
82  *        for DICOM compliance. Returns NULL on failure.
83  *        It will be up to the user to load the pixels into memory
84  *        (see GetImageData, GetImageDataRaw)
85  * \note  the in-memory representation of all available tags found in
86  *        the DICOM header is post-poned to first header information access.
87  *        This avoid a double parsing of public part of the header when
88  *        one sets an a posteriori shadow dictionary (efficiency can be
89  *        seen as a side effect).   
90  * @param filename file to be opened for parsing
91  */
92 File::File(std::string const & filename )
93 {
94    HeaderInternal = new Header( filename );
95    SelfHeader = true;
96    Initialise();
97 }
98
99 /**
100  * \brief canonical destructor
101  * \note  If the Header was created by the File constructor,
102  *        it is destroyed by the File
103  */
104 File::~File()
105
106    if( PixelReadConverter )
107    {
108       delete PixelReadConverter;
109    }
110    if( PixelWriteConverter )
111    {
112       delete PixelWriteConverter;
113    }
114    if( Archive )
115    {
116       delete Archive;
117    }
118
119    if( SelfHeader )
120    {
121       delete HeaderInternal;
122    }
123    HeaderInternal = 0;
124 }
125
126 //-----------------------------------------------------------------------------
127 // Print
128 void File::Print(std::ostream &os)
129 {
130    HeaderInternal->SetPrintLevel(PrintLevel);
131    HeaderInternal->Print(os);
132
133    PixelReadConverter->SetPrintLevel(PrintLevel);
134    PixelReadConverter->Print(os);
135 }
136
137 //-----------------------------------------------------------------------------
138 // Public
139 /**
140  * \brief   Get the size of the image data
141  * 
142  *          If the image can be RGB (with a lut or by default), the size 
143  *          corresponds to the RGB image
144  * @return  The image size
145  */
146 size_t File::GetImageDataSize()
147 {
148    if ( PixelWriteConverter->GetUserData() )
149    {
150       return PixelWriteConverter->GetUserDataSize();
151    }
152
153    return PixelReadConverter->GetRGBSize();
154 }
155
156 /**
157  * \brief   Get the size of the image data
158  * 
159  *          If the image can be RGB by transformation in a LUT, this
160  *          transformation isn't considered
161  * @return  The raw image size
162  */
163 size_t File::GetImageDataRawSize()
164 {
165    if ( PixelWriteConverter->GetUserData() )
166    {
167       return PixelWriteConverter->GetUserDataSize();
168    }
169
170    return PixelReadConverter->GetRawSize();
171 }
172
173 /**
174  * \brief   - Allocates necessary memory, 
175  *          - Reads the pixels from disk (uncompress if necessary),
176  *          - Transforms YBR pixels, if any, into RGB pixels
177  *          - Transforms 3 planes R, G, B, if any, into a single RGB Plane
178  *          - Transforms single Grey plane + 3 Palettes into a RGB Plane
179  *          - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
180  * @return  Pointer to newly allocated pixel data.
181  *          NULL if alloc fails 
182  */
183 uint8_t *File::GetImageData()
184 {
185    if ( PixelWriteConverter->GetUserData() )
186    {
187       return PixelWriteConverter->GetUserData();
188    }
189
190    if ( ! GetRaw() )
191    {
192       // If the decompression failed nothing can be done.
193       return 0;
194    }
195
196    if ( HeaderInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
197    {
198       return PixelReadConverter->GetRGB();
199    }
200    else
201    {
202       // When no LUT or LUT conversion fails, return the Raw
203       return PixelReadConverter->GetRaw();
204    }
205 }
206
207 /**
208  * \brief   Allocates necessary memory, 
209  *          Transforms YBR pixels (if any) into RGB pixels
210  *          Transforms 3 planes R, G, B  (if any) into a single RGB Plane
211  *          Copies the pixel data (image[s]/volume[s]) to newly allocated zone. 
212  *          DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
213  * @return  Pointer to newly allocated pixel data.
214  * \        NULL if alloc fails 
215  */
216 uint8_t *File::GetImageDataRaw ()
217 {
218    return GetRaw();
219 }
220
221 /**
222  * \brief
223  *          Read the pixels from disk (uncompress if necessary),
224  *          Transforms YBR pixels, if any, into RGB pixels
225  *          Transforms 3 planes R, G, B, if any, into a single RGB Plane
226  *          Transforms single Grey plane + 3 Palettes into a RGB Plane   
227  *          Copies at most MaxSize bytes of pixel data to caller allocated
228  *          memory space.
229  * \warning This function allows people that want to build a volume
230  *          from an image stack *not to* have, first to get the image pixels, 
231  *          and then move them to the volume area.
232  *          It's absolutely useless for any VTK user since vtk chooses 
233  *          to invert the lines of an image, that is the last line comes first
234  *          (for some axis related reasons?). Hence he will have 
235  *          to load the image line by line, starting from the end.
236  *          VTK users have to call GetImageData
237  *     
238  * @param   destination Address (in caller's memory space) at which the
239  *          pixel data should be copied
240  * @param   maxSize Maximum number of bytes to be copied. When MaxSize
241  *          is not sufficient to hold the pixel data the copy is not
242  *          executed (i.e. no partial copy).
243  * @return  On success, the number of bytes actually copied. Zero on
244  *          failure e.g. MaxSize is lower than necessary.
245  */
246 size_t File::GetImageDataIntoVector (void *destination, size_t maxSize)
247 {
248    if ( ! GetRaw() )
249    {
250       // If the decompression failed nothing can be done.
251       return 0;
252    }
253
254    if ( HeaderInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
255    {
256       if ( PixelReadConverter->GetRGBSize() > maxSize )
257       {
258          gdcmVerboseMacro( "Pixel data bigger than caller's expected MaxSize");
259          return 0;
260       }
261       memcpy( destination,
262               (void*)PixelReadConverter->GetRGB(),
263               PixelReadConverter->GetRGBSize() );
264       return PixelReadConverter->GetRGBSize();
265    }
266
267    // Either no LUT conversion necessary or LUT conversion failed
268    if ( PixelReadConverter->GetRawSize() > maxSize )
269    {
270       gdcmVerboseMacro( "Pixel data bigger than caller's expected MaxSize");
271       return 0;
272    }
273    memcpy( destination,
274            (void*)PixelReadConverter->GetRaw(),
275            PixelReadConverter->GetRawSize() );
276    return PixelReadConverter->GetRawSize();
277 }
278
279 /**
280  * \brief   Points the internal pointer to the callers inData
281  *          image representation, BUT WITHOUT COPYING THE DATA.
282  *          'image' Pixels are presented as C-like 2D arrays : line per line.
283  *          'volume'Pixels are presented as C-like 3D arrays : plane per plane 
284  * \warning Since the pixels are not copied, it is the caller's responsability
285  *          not to deallocate it's data before gdcm uses them (e.g. with
286  *          the Write() method.
287  * @param inData user supplied pixel area
288  * @param expectedSize total image size, in Bytes
289  *
290  * @return boolean
291  */
292 void File::SetImageData(uint8_t *inData, size_t expectedSize)
293 {
294    SetUserData(inData,expectedSize);
295 }
296
297 /**
298  * \brief   Set the image datas defined by the user
299  * \warning When writting the file, this datas are get as default datas to write
300  */
301 void File::SetUserData(uint8_t *data, size_t expectedSize)
302 {
303    PixelWriteConverter->SetUserData(data,expectedSize);
304 }
305
306 /**
307  * \brief   Get the image datas defined by the user
308  * \warning When writting the file, this datas are get as default data to write
309  */
310 uint8_t *File::GetUserData()
311 {
312    return PixelWriteConverter->GetUserData();
313 }
314
315 /**
316  * \brief   Get the image data size defined by the user
317  * \warning When writting the file, this datas are get as default data to write
318  */
319 size_t File::GetUserDataSize()
320 {
321    return PixelWriteConverter->GetUserDataSize();
322 }
323
324 /**
325  * \brief   Get the image datas from the file.
326  *          If a LUT is found, the data are expanded to be RGB
327  */
328 uint8_t *File::GetRGBData()
329 {
330    return PixelReadConverter->GetRGB();
331 }
332
333 /**
334  * \brief   Get the image data size from the file.
335  *          If a LUT is found, the data are expanded to be RGB
336  */
337 size_t File::GetRGBDataSize()
338 {
339    return PixelReadConverter->GetRGBSize();
340 }
341
342 /**
343  * \brief   Get the image datas from the file.
344  *          If a LUT is found, the datas are not expanded !
345  */
346 uint8_t *File::GetRawData()
347 {
348    return PixelReadConverter->GetRaw();
349 }
350
351 /**
352  * \brief   Get the image data size from the file.
353  *          If a LUT is found, the data are not expanded !
354  */
355 size_t File::GetRawDataSize()
356 {
357    return PixelReadConverter->GetRawSize();
358 }
359
360 /**
361  * \brief Writes on disk A SINGLE Dicom file
362  *        NO test is performed on  processor "Endiannity".
363  *        It's up to the user to call his Reader properly
364  * @param fileName name of the file to be created
365  *                 (any already existing file is over written)
366  * @return false if write fails
367  */
368
369 bool File::WriteRawData(std::string const &fileName)
370 {
371   std::ofstream fp1(fileName.c_str(), std::ios::out | std::ios::binary );
372    if (!fp1)
373    {
374       gdcmVerboseMacro( "Fail to open (write) file:" << fileName.c_str());
375       return false;
376    }
377
378    if( PixelWriteConverter->GetUserData() )
379    {
380       fp1.write( (char*)PixelWriteConverter->GetUserData(), 
381                  PixelWriteConverter->GetUserDataSize() );
382    }
383    else if ( PixelReadConverter->GetRGB() )
384    {
385       fp1.write( (char*)PixelReadConverter->GetRGB(), 
386                  PixelReadConverter->GetRGBSize());
387    }
388    else if ( PixelReadConverter->GetRaw() )
389    {
390       fp1.write( (char*)PixelReadConverter->GetRaw(), 
391                  PixelReadConverter->GetRawSize());
392    }
393    else
394    {
395       gdcmErrorMacro( "Nothing written." );
396    }
397
398    fp1.close();
399
400    return true;
401 }
402
403 /**
404  * \brief Writes on disk A SINGLE Dicom file, 
405  *        using the Implicit Value Representation convention
406  *        NO test is performed on  processor "Endiannity".
407  * @param fileName name of the file to be created
408  *                 (any already existing file is overwritten)
409  * @return false if write fails
410  */
411
412 bool File::WriteDcmImplVR (std::string const &fileName)
413 {
414    SetWriteTypeToDcmImplVR();
415    return Write(fileName);
416 }
417
418 /**
419 * \brief Writes on disk A SINGLE Dicom file, 
420  *        using the Explicit Value Representation convention
421  *        NO test is performed on  processor "Endiannity". 
422  * @param fileName name of the file to be created
423  *                 (any already existing file is overwritten)
424  * @return false if write fails
425  */
426
427 bool File::WriteDcmExplVR (std::string const &fileName)
428 {
429    SetWriteTypeToDcmExplVR();
430    return Write(fileName);
431 }
432
433 /**
434  * \brief Writes on disk A SINGLE Dicom file, 
435  *        using the ACR-NEMA convention
436  *        NO test is performed on  processor "Endiannity".
437  *        (a l'attention des logiciels cliniques 
438  *        qui ne prennent en entrée QUE des images ACR ...
439  * \warning if a DICOM_V3 header is supplied,
440  *         groups < 0x0008 and shadow groups are ignored
441  * \warning NO TEST is performed on processor "Endiannity".
442  * @param fileName name of the file to be created
443  *                 (any already existing file is overwritten)
444  * @return false if write fails
445  */
446
447 bool File::WriteAcr (std::string const &fileName)
448 {
449    SetWriteTypeToAcr();
450    return Write(fileName);
451 }
452
453 /**
454  * \brief Writes on disk A SINGLE Dicom file, 
455  * @param fileName name of the file to be created
456  *                 (any already existing file is overwritten)
457  * @return false if write fails
458  */
459 bool File::Write(std::string const &fileName)
460 {
461    switch(WriteType)
462    {
463       case ImplicitVR:
464          SetWriteFileTypeToImplicitVR();
465          break;
466       case ExplicitVR:
467          SetWriteFileTypeToExplicitVR();
468          break;
469       case ACR:
470       case ACR_LIBIDO:
471          SetWriteFileTypeToACR();
472          break;
473       default:
474          SetWriteFileTypeToExplicitVR();
475    }
476
477    // --------------------------------------------------------------
478    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
479    //
480    // if recognition code tells us we dealt with a LibIDO image
481    // we reproduce on disk the switch between lineNumber and columnNumber
482    // just before writting ...
483    /// \todo the best trick would be *change* the recognition code
484    ///       but pb expected if user deals with, e.g. COMPLEX images
485    if( WriteType == ACR_LIBIDO )
486    {
487       SetWriteToLibido();
488    }
489    else
490    {
491       SetWriteToNoLibido();
492    }
493    // ----------------- End of Special Patch ----------------
494   
495    switch(WriteMode)
496    {
497       case WMODE_RAW :
498          SetWriteToRaw();
499          break;
500       case WMODE_RGB :
501          SetWriteToRGB();
502          break;
503    }
504
505    bool check = CheckWriteIntegrity();
506    if(check)
507    {
508       check = HeaderInternal->Write(fileName,WriteType);
509    }
510
511    RestoreWrite();
512    RestoreWriteFileType();
513
514    // --------------------------------------------------------------
515    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
516    // 
517    // ...and we restore the Header to be Dicom Compliant again 
518    // just after writting
519    RestoreWriteOfLibido();
520    // ----------------- End of Special Patch ----------------
521
522    return check;
523 }
524
525 /**
526  * \brief   Accesses an existing DocEntry (i.e. a Dicom Element)
527  *          through it's (group, element) and modifies it's content with
528  *          the given value.
529  * @param   content new value (string) to substitute with
530  * @param   group     group number of the Dicom Element to modify
531  * @param   element element number of the Dicom Element to modify
532  */
533 bool File::SetEntry(std::string const &content,
534                     uint16_t group, uint16_t element)
535
536    return HeaderInternal->SetEntry(content,group,element);
537 }
538
539
540 /**
541  * \brief   Accesses an existing DocEntry (i.e. a Dicom Element)
542  *          through it's (group, element) and modifies it's content with
543  *          the given value.
544  * @param   content new value (void*  -> uint8_t*) to substitute with
545  * @param   lgth new value length
546  * @param   group     group number of the Dicom Element to modify
547  * @param   element element number of the Dicom Element to modify
548  */
549 bool File::SetEntry(uint8_t *content, int lgth,
550                     uint16_t group, uint16_t element)
551 {
552    return HeaderInternal->SetEntry(content,lgth,group,element);
553 }
554
555 /**
556  * \brief   Modifies the value of a given Doc Entry (Dicom Element)
557  *          when it exists. Create it with the given value when unexistant.
558  * @param   content (string) Value to be set
559  * @param   group   Group number of the Entry 
560  * @param   element  Element number of the Entry
561  * \return  pointer to the modified/created Header Entry (NULL when creation
562  *          failed).
563  */ 
564 bool File::ReplaceOrCreate(std::string const &content,
565                            uint16_t group, uint16_t element)
566 {
567    return HeaderInternal->ReplaceOrCreate(content,group,element) != NULL;
568 }
569
570 /*
571  * \brief   Modifies the value of a given Header Entry (Dicom Element)
572  *          when it exists. Create it with the given value when unexistant.
573  *          A copy of the binArea is made to be kept in the Document.
574  * @param   binArea (binary) value to be set
575  * @param   group   Group number of the Entry 
576  * @param   element  Element number of the Entry
577  * \return  pointer to the modified/created Header Entry (NULL when creation
578  *          failed).
579  */
580 bool File::ReplaceOrCreate(uint8_t *binArea, int lgth,
581                            uint16_t group, uint16_t element)
582 {
583    return HeaderInternal->ReplaceOrCreate(binArea,lgth,group,element) != NULL;
584 }
585
586 /**
587  * \brief Access to the underlying \ref PixelReadConverter RGBA LUT
588  */
589 uint8_t* File::GetLutRGBA()
590 {
591    return PixelReadConverter->GetLutRGBA();
592 }
593
594 //-----------------------------------------------------------------------------
595 // Protected
596
597 /**
598  * \brief Check the write integrity
599  *
600  * The tests made are :
601  *  - verify the size of the image to write with the possible write
602  *    when the user set an image data
603  * @return true if the check successfulls
604  */
605 bool File::CheckWriteIntegrity()
606 {
607    if(PixelWriteConverter->GetUserData())
608    {
609       int numberBitsAllocated = HeaderInternal->GetBitsAllocated();
610       if ( numberBitsAllocated == 0 || numberBitsAllocated == 12 )
611       {
612          numberBitsAllocated = 16;
613       }
614
615       size_t decSize = HeaderInternal->GetXSize()
616                     * HeaderInternal->GetYSize() 
617                     * HeaderInternal->GetZSize()
618                     * ( numberBitsAllocated / 8 )
619                     * HeaderInternal->GetSamplesPerPixel();
620       size_t rgbSize = decSize;
621       if( HeaderInternal->HasLUT() )
622          rgbSize = decSize * 3;
623
624       switch(WriteMode)
625       {
626          case WMODE_RAW :
627             if( decSize!=PixelWriteConverter->GetUserDataSize() )
628             {
629                gdcmVerboseMacro( "Data size is incorrect (Raw)" << decSize 
630                     << " / " << PixelWriteConverter->GetUserDataSize() );
631                return false;
632             }
633             break;
634          case WMODE_RGB :
635             if( rgbSize!=PixelWriteConverter->GetUserDataSize() )
636             {
637                gdcmVerboseMacro( "Data size is incorrect (RGB)" << decSize
638                    << " / " << PixelWriteConverter->GetUserDataSize() );
639                return false;
640             }
641             break;
642       }
643    }
644    
645    return true;
646 }
647
648 void File::SetWriteToRaw()
649 {
650    if(HeaderInternal->GetNumberOfScalarComponents()==3 && !HeaderInternal->HasLUT())
651    {
652       SetWriteToRGB();
653    } 
654    else
655    {
656       ValEntry *photInt = CopyValEntry(0x0028,0x0004);
657       if(HeaderInternal->HasLUT())
658       {
659          photInt->SetValue("PALETTE COLOR ");
660       }
661       else
662       {
663          photInt->SetValue("MONOCHROME1 ");
664       }
665
666       PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
667                                        PixelReadConverter->GetRawSize());
668
669       BinEntry *pixel = CopyBinEntry(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
670       pixel->SetValue(GDCM_BINLOADED);
671       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
672       pixel->SetLength(PixelWriteConverter->GetDataSize());
673
674       Archive->Push(photInt);
675       Archive->Push(pixel);
676    }
677 }
678
679 void File::SetWriteToRGB()
680 {
681    if(HeaderInternal->GetNumberOfScalarComponents()==3)
682    {
683       PixelReadConverter->BuildRGBImage();
684       
685       ValEntry *spp = CopyValEntry(0x0028,0x0002);
686       spp->SetValue("3 ");
687
688       ValEntry *planConfig = CopyValEntry(0x0028,0x0006);
689       planConfig->SetValue("0 ");
690
691       ValEntry *photInt = CopyValEntry(0x0028,0x0004);
692       photInt->SetValue("RGB ");
693
694       if(PixelReadConverter->GetRGB())
695       {
696          PixelWriteConverter->SetReadData(PixelReadConverter->GetRGB(),
697                                           PixelReadConverter->GetRGBSize());
698       }
699       else // Raw data
700       {
701          PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
702                                           PixelReadConverter->GetRawSize());
703       }
704
705       BinEntry *pixel = CopyBinEntry(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
706       pixel->SetValue(GDCM_BINLOADED);
707       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
708       pixel->SetLength(PixelWriteConverter->GetDataSize());
709
710       Archive->Push(spp);
711       Archive->Push(planConfig);
712       Archive->Push(photInt);
713       Archive->Push(pixel);
714
715       // Remove any LUT
716       Archive->Push(0x0028,0x1101);
717       Archive->Push(0x0028,0x1102);
718       Archive->Push(0x0028,0x1103);
719       Archive->Push(0x0028,0x1201);
720       Archive->Push(0x0028,0x1202);
721       Archive->Push(0x0028,0x1203);
722
723       // For old ACR-NEMA
724       // Thus, we have a RGB image and the bits allocated = 24 and 
725       // samples per pixels = 1 (in the read file)
726       if(HeaderInternal->GetBitsAllocated()==24) 
727       {
728          ValEntry *bitsAlloc = CopyValEntry(0x0028,0x0100);
729          bitsAlloc->SetValue("8 ");
730
731          ValEntry *bitsStored = CopyValEntry(0x0028,0x0101);
732          bitsStored->SetValue("8 ");
733
734          ValEntry *highBit = CopyValEntry(0x0028,0x0102);
735          highBit->SetValue("7 ");
736
737          Archive->Push(bitsAlloc);
738          Archive->Push(bitsStored);
739          Archive->Push(highBit);
740       }
741    }
742    else
743    {
744       SetWriteToRaw();
745    }
746 }
747
748 void File::RestoreWrite()
749 {
750    Archive->Restore(0x0028,0x0002);
751    Archive->Restore(0x0028,0x0004);
752    Archive->Restore(0x0028,0x0006);
753    Archive->Restore(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
754
755    // For old ACR-NEMA (24 bits problem)
756    Archive->Restore(0x0028,0x0100);
757    Archive->Restore(0x0028,0x0101);
758    Archive->Restore(0x0028,0x0102);
759
760    // For the LUT
761    Archive->Restore(0x0028,0x1101);
762    Archive->Restore(0x0028,0x1102);
763    Archive->Restore(0x0028,0x1103);
764    Archive->Restore(0x0028,0x1201);
765    Archive->Restore(0x0028,0x1202);
766    Archive->Restore(0x0028,0x1203);
767 }
768
769 void File::SetWriteFileTypeToACR()
770 {
771    Archive->Push(0x0002,0x0010);
772 }
773
774 void File::SetWriteFileTypeToExplicitVR()
775 {
776    std::string ts = Util::DicomString( 
777       Document::GetTransferSyntaxValue(ExplicitVRLittleEndian).c_str() );
778
779    ValEntry *tss = CopyValEntry(0x0002,0x0010);
780    tss->SetValue(ts);
781
782    Archive->Push(tss);
783 }
784
785 void File::SetWriteFileTypeToImplicitVR()
786 {
787    std::string ts = Util::DicomString(
788       Document::GetTransferSyntaxValue(ImplicitVRLittleEndian).c_str() );
789
790    ValEntry *tss = CopyValEntry(0x0002,0x0010);
791    tss->SetValue(ts);
792
793    Archive->Push(tss);
794 }
795
796 void File::RestoreWriteFileType()
797 {
798    Archive->Restore(0x0002,0x0010);
799 }
800
801 void File::SetWriteToLibido()
802 {
803    ValEntry *oldRow = dynamic_cast<ValEntry *>
804                 (HeaderInternal->GetDocEntry(0x0028, 0x0010));
805    ValEntry *oldCol = dynamic_cast<ValEntry *>
806                 (HeaderInternal->GetDocEntry(0x0028, 0x0011));
807    
808    if( oldRow && oldCol )
809    {
810       std::string rows, columns; 
811
812       ValEntry *newRow=new ValEntry(oldRow->GetDictEntry());
813       ValEntry *newCol=new ValEntry(oldCol->GetDictEntry());
814
815       newRow->Copy(oldCol);
816       newCol->Copy(oldRow);
817
818       newRow->SetValue(oldCol->GetValue());
819       newCol->SetValue(oldRow->GetValue());
820
821       Archive->Push(newRow);
822       Archive->Push(newCol);
823    }
824
825    ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
826    libidoCode->SetValue("ACRNEMA_LIBIDO_1.1");
827    Archive->Push(libidoCode);
828 }
829
830 void File::SetWriteToNoLibido()
831 {
832    ValEntry *recCode = dynamic_cast<ValEntry *>
833                 (HeaderInternal->GetDocEntry(0x0008,0x0010));
834    if( recCode )
835    {
836       if( recCode->GetValue() == "ACRNEMA_LIBIDO_1.1" )
837       {
838          ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
839          libidoCode->SetValue("");
840          Archive->Push(libidoCode);
841       }
842    }
843 }
844
845 void File::RestoreWriteOfLibido()
846 {
847    Archive->Restore(0x0028,0x0010);
848    Archive->Restore(0x0028,0x0011);
849    Archive->Restore(0x0008,0x0010);
850 }
851
852 ValEntry *File::CopyValEntry(uint16_t group,uint16_t element)
853 {
854    DocEntry *oldE = HeaderInternal->GetDocEntry(group, element);
855    ValEntry *newE;
856
857    if(oldE)
858    {
859       newE = new ValEntry(oldE->GetDictEntry());
860       newE->Copy(oldE);
861    }
862    else
863    {
864       newE = GetHeader()->NewValEntry(group,element);
865    }
866
867    return(newE);
868 }
869
870 BinEntry *File::CopyBinEntry(uint16_t group,uint16_t element)
871 {
872    DocEntry *oldE = HeaderInternal->GetDocEntry(group, element);
873    BinEntry *newE;
874
875    if(oldE)
876    {
877       newE = new BinEntry(oldE->GetDictEntry());
878       newE->Copy(oldE);
879    }
880    else
881    {
882       newE = GetHeader()->NewBinEntry(group,element);
883    }
884
885    return(newE);
886 }
887
888 //-----------------------------------------------------------------------------
889 // Protected
890 /**
891  * \brief Factorization for various forms of constructors.
892  */
893 void File::Initialise()
894 {
895    WriteMode = WMODE_RAW;
896    WriteType = ExplicitVR;
897
898    PixelReadConverter = new PixelReadConvert;
899    PixelWriteConverter = new PixelWriteConvert;
900    Archive = new DocEntryArchive( HeaderInternal );
901
902    if ( HeaderInternal->IsReadable() )
903    {
904       PixelReadConverter->GrabInformationsFromHeader( HeaderInternal );
905    }
906 }
907
908 uint8_t *File::GetRaw()
909 {
910    uint8_t *raw = PixelReadConverter->GetRaw();
911    if ( ! raw )
912    {
913       // The Raw image migth not be loaded yet:
914       std::ifstream *fp = HeaderInternal->OpenFile();
915       PixelReadConverter->ReadAndDecompressPixelData( fp );
916       if(fp) 
917          HeaderInternal->CloseFile();
918
919       raw = PixelReadConverter->GetRaw();
920       if ( ! raw )
921       {
922          gdcmVerboseMacro( "Read/decompress of pixel data apparently went wrong.");
923          return 0;
924       }
925    }
926
927    return raw;
928 }
929
930 //-----------------------------------------------------------------------------
931 // Private
932
933 //-----------------------------------------------------------------------------
934 } // end namespace gdcm
935