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