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