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