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