]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
d83dd3f50e4c3aed3f35fcaced7d045fae811ea9
[gdcm.git] / src / gdcmFile.cxx
1   /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmFile.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/01/11 00:21:48 $
7   Version:   $Revision: 1.188 $
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 
651     && !HeaderInternal->HasLUT())
652    {
653       SetWriteToRGB();
654    } 
655    else
656    {
657       ValEntry *photInt = CopyValEntry(0x0028,0x0004);
658       if(HeaderInternal->HasLUT())
659       {
660          photInt->SetValue("PALETTE COLOR ");
661       }
662       else
663       {
664          photInt->SetValue("MONOCHROME1 ");
665       }
666
667       PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
668                                        PixelReadConverter->GetRawSize());
669
670       BinEntry *pixel = 
671          CopyBinEntry(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
672       pixel->SetValue(GDCM_BINLOADED);
673       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
674       pixel->SetLength(PixelWriteConverter->GetDataSize());
675
676       Archive->Push(photInt);
677       Archive->Push(pixel);
678    }
679 }
680
681 void File::SetWriteToRGB()
682 {
683    if(HeaderInternal->GetNumberOfScalarComponents()==3)
684    {
685       PixelReadConverter->BuildRGBImage();
686       
687       ValEntry *spp = CopyValEntry(0x0028,0x0002);
688       spp->SetValue("3 ");
689
690       ValEntry *planConfig = CopyValEntry(0x0028,0x0006);
691       planConfig->SetValue("0 ");
692
693       ValEntry *photInt = CopyValEntry(0x0028,0x0004);
694       photInt->SetValue("RGB ");
695
696       if(PixelReadConverter->GetRGB())
697       {
698          PixelWriteConverter->SetReadData(PixelReadConverter->GetRGB(),
699                                           PixelReadConverter->GetRGBSize());
700       }
701       else // Raw data
702       {
703          PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
704                                           PixelReadConverter->GetRawSize());
705       }
706
707       BinEntry *pixel = 
708          CopyBinEntry(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
709       pixel->SetValue(GDCM_BINLOADED);
710       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
711       pixel->SetLength(PixelWriteConverter->GetDataSize());
712
713       Archive->Push(spp);
714       Archive->Push(planConfig);
715       Archive->Push(photInt);
716       Archive->Push(pixel);
717
718       // Remove any LUT
719       Archive->Push(0x0028,0x1101);
720       Archive->Push(0x0028,0x1102);
721       Archive->Push(0x0028,0x1103);
722       Archive->Push(0x0028,0x1201);
723       Archive->Push(0x0028,0x1202);
724       Archive->Push(0x0028,0x1203);
725
726       // For old ACR-NEMA
727       // Thus, we have a RGB image and the bits allocated = 24 and 
728       // samples per pixels = 1 (in the read file)
729       if(HeaderInternal->GetBitsAllocated()==24) 
730       {
731          ValEntry *bitsAlloc = CopyValEntry(0x0028,0x0100);
732          bitsAlloc->SetValue("8 ");
733
734          ValEntry *bitsStored = CopyValEntry(0x0028,0x0101);
735          bitsStored->SetValue("8 ");
736
737          ValEntry *highBit = CopyValEntry(0x0028,0x0102);
738          highBit->SetValue("7 ");
739
740          Archive->Push(bitsAlloc);
741          Archive->Push(bitsStored);
742          Archive->Push(highBit);
743       }
744    }
745    else
746    {
747       SetWriteToRaw();
748    }
749 }
750
751 void File::RestoreWrite()
752 {
753    Archive->Restore(0x0028,0x0002);
754    Archive->Restore(0x0028,0x0004);
755    Archive->Restore(0x0028,0x0006);
756    Archive->Restore(GetHeader()->GetGrPixel(),GetHeader()->GetNumPixel());
757
758    // For old ACR-NEMA (24 bits problem)
759    Archive->Restore(0x0028,0x0100);
760    Archive->Restore(0x0028,0x0101);
761    Archive->Restore(0x0028,0x0102);
762
763    // For the LUT
764    Archive->Restore(0x0028,0x1101);
765    Archive->Restore(0x0028,0x1102);
766    Archive->Restore(0x0028,0x1103);
767    Archive->Restore(0x0028,0x1201);
768    Archive->Restore(0x0028,0x1202);
769    Archive->Restore(0x0028,0x1203);
770 }
771
772 void File::SetWriteFileTypeToACR()
773 {
774    Archive->Push(0x0002,0x0010);
775 }
776
777 void File::SetWriteFileTypeToExplicitVR()
778 {
779    std::string ts = Util::DicomString( 
780       Document::GetTransferSyntaxValue(ExplicitVRLittleEndian).c_str() );
781
782    ValEntry *tss = CopyValEntry(0x0002,0x0010);
783    tss->SetValue(ts);
784
785    Archive->Push(tss);
786 }
787
788 void File::SetWriteFileTypeToImplicitVR()
789 {
790    std::string ts = Util::DicomString(
791       Document::GetTransferSyntaxValue(ImplicitVRLittleEndian).c_str() );
792
793    ValEntry *tss = CopyValEntry(0x0002,0x0010);
794    tss->SetValue(ts);
795
796    Archive->Push(tss);
797 }
798
799 void File::RestoreWriteFileType()
800 {
801    Archive->Restore(0x0002,0x0010);
802 }
803
804 void File::SetWriteToLibido()
805 {
806    ValEntry *oldRow = dynamic_cast<ValEntry *>
807                 (HeaderInternal->GetDocEntry(0x0028, 0x0010));
808    ValEntry *oldCol = dynamic_cast<ValEntry *>
809                 (HeaderInternal->GetDocEntry(0x0028, 0x0011));
810    
811    if( oldRow && oldCol )
812    {
813       std::string rows, columns; 
814
815       ValEntry *newRow=new ValEntry(oldRow->GetDictEntry());
816       ValEntry *newCol=new ValEntry(oldCol->GetDictEntry());
817
818       newRow->Copy(oldCol);
819       newCol->Copy(oldRow);
820
821       newRow->SetValue(oldCol->GetValue());
822       newCol->SetValue(oldRow->GetValue());
823
824       Archive->Push(newRow);
825       Archive->Push(newCol);
826    }
827
828    ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
829    libidoCode->SetValue("ACRNEMA_LIBIDO_1.1");
830    Archive->Push(libidoCode);
831 }
832
833 void File::SetWriteToNoLibido()
834 {
835    ValEntry *recCode = dynamic_cast<ValEntry *>
836                 (HeaderInternal->GetDocEntry(0x0008,0x0010));
837    if( recCode )
838    {
839       if( recCode->GetValue() == "ACRNEMA_LIBIDO_1.1" )
840       {
841          ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
842          libidoCode->SetValue("");
843          Archive->Push(libidoCode);
844       }
845    }
846 }
847
848 void File::RestoreWriteOfLibido()
849 {
850    Archive->Restore(0x0028,0x0010);
851    Archive->Restore(0x0028,0x0011);
852    Archive->Restore(0x0008,0x0010);
853 }
854
855 ValEntry *File::CopyValEntry(uint16_t group,uint16_t element)
856 {
857    DocEntry *oldE = HeaderInternal->GetDocEntry(group, element);
858    ValEntry *newE;
859
860    if(oldE)
861    {
862       newE = new ValEntry(oldE->GetDictEntry());
863       newE->Copy(oldE);
864    }
865    else
866    {
867       newE = GetHeader()->NewValEntry(group,element);
868    }
869
870    return newE;
871 }
872
873 BinEntry *File::CopyBinEntry(uint16_t group,uint16_t element)
874 {
875    DocEntry *oldE = HeaderInternal->GetDocEntry(group, element);
876    BinEntry *newE;
877
878    if(oldE)
879    {
880       newE = new BinEntry(oldE->GetDictEntry());
881       newE->Copy(oldE);
882    }
883    else
884    {
885       newE = GetHeader()->NewBinEntry(group,element);
886    }
887
888    return newE;
889 }
890
891 //-----------------------------------------------------------------------------
892 // Protected
893 /**
894  * \brief Factorization for various forms of constructors.
895  */
896 void File::Initialise()
897 {
898    WriteMode = WMODE_RAW;
899    WriteType = ExplicitVR;
900
901    PixelReadConverter = new PixelReadConvert;
902    PixelWriteConverter = new PixelWriteConvert;
903    Archive = new DocEntryArchive( HeaderInternal );
904
905    if ( HeaderInternal->IsReadable() )
906    {
907       PixelReadConverter->GrabInformationsFromHeader( HeaderInternal );
908    }
909 }
910
911 uint8_t *File::GetRaw()
912 {
913    uint8_t *raw = PixelReadConverter->GetRaw();
914    if ( ! raw )
915    {
916       // The Raw image migth not be loaded yet:
917       std::ifstream *fp = HeaderInternal->OpenFile();
918       PixelReadConverter->ReadAndDecompressPixelData( fp );
919       if(fp) 
920          HeaderInternal->CloseFile();
921
922       raw = PixelReadConverter->GetRaw();
923       if ( ! raw )
924       {
925          gdcmVerboseMacro( "Read/decompress of pixel data apparently went wrong.");
926          return 0;
927       }
928    }
929
930    return raw;
931 }
932
933 //-----------------------------------------------------------------------------
934 // Private
935
936 //-----------------------------------------------------------------------------
937 } // end namespace gdcm
938