]> Creatis software - gdcm.git/blob - vtk/vtkGdcmReader.cxx
Remove useless variable, to avoid warning
[gdcm.git] / vtk / vtkGdcmReader.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: vtkGdcmReader.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/09/20 08:50:57 $
7   Version:   $Revision: 1.84 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18                                                                                 
19 //-----------------------------------------------------------------------------
20 // //////////////////////////////////////////////////////////////
21 //
22 //===>  Many users expect from vtkGdcmReader it 'orders' the images
23 //     (that's the job of gdcm::SerieHelper ...)
24 //     When user *knows* the files with same Serie UID 
25 //        have same sizes, same 'pixel' type, same color convention, ...
26 //     the right way to proceed is as follow :
27 //
28 //      gdcm::SerieHelper *sh= new gdcm::SerieHelper();
29 //      // if user wants *not* to load some parts of the file headers
30 //      sh->SetLoadMode(loadMode);
31 //      // if user wants *not* to load some files 
32 //      sh->AddRestriction(group, element, value, operator);
33 //      sh->AddRestriction( ...
34 //      sh->SetDirectory(directoryWithImages);
35 //
36 //      // if user wants to sort reverse order
37 //      sh->SetSortOrderToReverse(); 
38 //      // here, we suppose only the first Coherent File List is of interest
39 //      gdcm::FileList *l = sh->GetFirstCoherentFileList();
40 //      // if user is doesn't trust too much the files with same Serie UID 
41 //      if ( !sh->IsCoherent(l) )
42 //         return; // not same sizes, same 'pixel' type -> stop
43 //      sh->OrderFileList(l);        // sort the list
44 //
45 //      vtkGdcmReader *reader = vtkGdcmReader::New();
46 //      // if user wants to modify pixel order (Mirror, TopDown, 90°Rotate, ...)
47 //      // he has to supply the function that does the job 
48 //      // (a *very* simple example is given in vtkgdcmSerieViewer.cxx)
49 //      reader->SetUserFunction (userSuppliedFunction);
50 //      // to pass a 'Coherent File List' as produced by gdcm::SerieHelper
51 //      reader->SetCoherentFileList(l); 
52 //      reader->Update();
53 //
54 // WARNING TODO CLEANME 
55 // Actual limitations of this code 
56 //  when a Coherent File List from SerieHelper is not used (bad idea :-(
57 //
58 // //////////////////////////////////////////////////////////////
59
60 #include "gdcmFileHelper.h"
61 #include "gdcmFile.h"
62
63 #include "vtkGdcmReader.h"
64 #include "gdcmDebug.h"
65 #include "gdcmCommon.h"
66
67 #include <vtkObjectFactory.h>
68 #include <vtkImageData.h>
69 #include <vtkPointData.h>
70 #include <vtkLookupTable.h>
71
72 vtkCxxRevisionMacro(vtkGdcmReader, "$Revision: 1.84 $")
73 vtkStandardNewMacro(vtkGdcmReader)
74
75 //-----------------------------------------------------------------------------
76 // Constructor / Destructor
77 vtkGdcmReader::vtkGdcmReader()
78 {
79    this->LookupTable = NULL;
80    this->AllowLookupTable = false;
81    this->AllowLightChecking = false;
82    this->LoadMode = gdcm::LD_ALL; // Load everything (possible values : 
83                                  //  - LD_NOSEQ, 
84                                  //  - LD_NOSHADOW,
85                                  //  - LD_NOSHADOWSEQ)
86    this->CoherentFileList = 0;
87    this->UserFunction     = 0;
88
89    this->OwnFile=true;
90    this->Execution=false;
91 }
92
93 vtkGdcmReader::~vtkGdcmReader()
94 {
95    this->RemoveAllFileName();
96    this->InternalFileNameList.clear();
97    if(this->LookupTable) 
98       this->LookupTable->Delete();
99 }
100
101 //-----------------------------------------------------------------------------
102 // Print
103 void vtkGdcmReader::PrintSelf(ostream &os, vtkIndent indent)
104 {
105    this->Superclass::PrintSelf(os,indent);
106    os << indent << "Filenames  : " << endl;
107    vtkIndent nextIndent = indent.GetNextIndent();
108    for (std::list<std::string>::iterator it = FileNameList.begin();
109         it != FileNameList.end();
110         ++it)
111    {
112       os << nextIndent << it->c_str() << endl ;
113    }
114 }
115
116 //-----------------------------------------------------------------------------
117 // Public
118 /*
119  * Remove all files from the list of images to read.
120  */
121 void vtkGdcmReader::RemoveAllFileName(void)
122 {
123    this->FileNameList.clear();
124    this->Modified();
125 }
126
127 /*
128  * Adds a file name to the list of images to read.
129  */
130 void vtkGdcmReader::AddFileName(const char* name)
131 {
132    // We need to bypass the const pointer [since list<>.push_bash() only
133    // takes a char* (but not a const char*)] by making a local copy:
134    this->FileNameList.push_back(name);
135    this->Modified();
136 }
137
138 /*
139  * Sets up a filename to be read.
140  */
141 void vtkGdcmReader::SetFileName(const char *name) 
142 {
143    vtkImageReader2::SetFileName(name);
144    // Since we maintain a list of filenames, when building a volume,
145    // (see vtkGdcmReader::AddFileName), we additionaly need to purge
146    // this list when we manually positionate the filename.
147    vtkDebugMacro(<< "Clearing all files given with AddFileName");
148    this->FileNameList.clear();
149    this->Modified();
150 }
151
152 //-----------------------------------------------------------------------------
153 // Protected
154 /*
155  * Configure the output e.g. WholeExtent, spacing, origin, scalar type...
156  */
157 void vtkGdcmReader::ExecuteInformation()
158 {
159    if(this->Execution)
160       return;
161
162    this->Execution=true;
163    this->RemoveAllInternalFile();
164    if(this->MTime>this->fileTime)
165    {
166       this->TotalNumberOfPlanes = 0;
167
168       if ( this->CoherentFileList != 0 )
169       {
170          this->UpdateFileInformation();
171       }
172       else
173       {
174          this->BuildFileListFromPattern();
175          this->LoadFileInformation();
176       }
177
178       if ( this->TotalNumberOfPlanes == 0)
179       {
180          vtkErrorMacro(<< "File set is not coherent. Exiting...");
181          return;
182       }
183
184       // if the user has not set the extent, but has set the VOI
185       // set the z axis extent to the VOI z axis
186       if (this->DataExtent[4]==0 && this->DataExtent[5] == 0 &&
187          (this->DataVOI[4] || this->DataVOI[5]))
188       {
189          this->DataExtent[4] = this->DataVOI[4];
190          this->DataExtent[5] = this->DataVOI[5];
191       }
192
193       // When the user has set the VOI, check it's coherence with the file content.
194       if (this->DataVOI[0] || this->DataVOI[1] || 
195       this->DataVOI[2] || this->DataVOI[3] ||
196       this->DataVOI[4] || this->DataVOI[5])
197       { 
198          if ((this->DataVOI[0] < 0) ||
199              (this->DataVOI[1] >= this->NumColumns) ||
200              (this->DataVOI[2] < 0) ||
201              (this->DataVOI[3] >= this->NumLines) ||
202              (this->DataVOI[4] < 0) ||
203              (this->DataVOI[5] >= this->TotalNumberOfPlanes ))
204          {
205             vtkWarningMacro(<< "The requested VOI is larger than expected extent.");
206             this->DataVOI[0] = 0;
207             this->DataVOI[1] = this->NumColumns - 1;
208             this->DataVOI[2] = 0;
209             this->DataVOI[3] = this->NumLines - 1;
210             this->DataVOI[4] = 0;
211             this->DataVOI[5] = this->TotalNumberOfPlanes - 1;
212          }
213       }
214
215       // Set the Extents.
216       this->DataExtent[0] = 0;
217       this->DataExtent[1] = this->NumColumns - 1;
218       this->DataExtent[2] = 0;
219       this->DataExtent[3] = this->NumLines - 1;
220       this->DataExtent[4] = 0;
221       this->DataExtent[5] = this->TotalNumberOfPlanes - 1;
222   
223       // We don't need to set the Endian related stuff (by using
224       // this->SetDataByteOrderToBigEndian() or SetDataByteOrderToLittleEndian()
225       // since the reading of the file is done by gdcm.
226       // But we do need to set up the data type for downstream filters:
227       if      ( ImageType == "8U" )
228       {
229          vtkDebugMacro(<< "8 bits unsigned image");
230          this->SetDataScalarTypeToUnsignedChar(); 
231       }
232       else if ( ImageType == "8S" )
233       {
234          vtkErrorMacro(<< "Cannot handle 8 bit signed files");
235          return;
236       }
237       else if ( ImageType == "16U" )
238       {
239          vtkDebugMacro(<< "16 bits unsigned image");
240          this->SetDataScalarTypeToUnsignedShort();
241       }
242       else if ( ImageType == "16S" )
243       {
244          vtkDebugMacro(<< "16 bits signed image");
245          this->SetDataScalarTypeToShort();
246       }
247       else if ( ImageType == "32U" )
248       {
249          vtkDebugMacro(<< "32 bits unsigned image");
250          vtkDebugMacro(<< "WARNING: forced to signed int !");
251          this->SetDataScalarTypeToInt();
252       }
253       else if ( ImageType == "32S" )
254       {
255          vtkDebugMacro(<< "32 bits signed image");
256          this->SetDataScalarTypeToInt();
257       }
258       else if ( ImageType == "FD" )
259       {
260          vtkDebugMacro(<< "64 bits Double image");
261          this->SetDataScalarTypeToDouble();
262       }
263       //Set number of scalar components:
264       this->SetNumberOfScalarComponents(this->NumComponents);
265
266       this->fileTime=this->MTime;
267    }
268
269    this->Superclass::ExecuteInformation();
270
271    this->GetOutput()->SetUpdateExtentToWholeExtent();
272    this->BuildData(this->GetOutput());
273
274    this->Execution=false;
275    this->RemoveAllInternalFile();
276 }
277  
278 /*
279  * Update => ouput->Update => UpdateData => Execute => ExecuteData 
280  * (see vtkSource.cxx for last step).
281  * This function (redefinition of vtkImageReader::ExecuteData, see 
282  * VTK/IO/vtkImageReader.cxx) reads a data from a file. The data
283  * extent/axes are assumed to be the same as the file extent/order.
284  */
285 void vtkGdcmReader::ExecuteData(vtkDataObject *output)
286 {
287    vtkImageData *data=vtkImageData::SafeDownCast(output);
288    data->SetExtent(this->DataExtent);
289
290 /*   if ( CoherentFileList != 0 )   // When a list of names is passed
291    {
292       if (this->CoherentFileList->empty())
293       {
294          vtkErrorMacro(<< "Coherent File List must have at least a valid File*.");
295          return;
296       }
297    }
298    else if (this->InternalFileNameList.empty())
299    {
300       vtkErrorMacro(<< "A least a valid FileName must be specified.");
301       return;
302    }
303 */
304 }
305
306 void vtkGdcmReader::BuildData(vtkDataObject *output)
307 {
308    vtkImageData *data = this->AllocateOutputData(output);
309
310    data->GetPointData()->GetScalars()->SetName("DicomImage-Volume");
311
312    // Test if output has valid extent
313    // Prevent memory errors
314    if((this->DataExtent[1]-this->DataExtent[0]>=0) &&
315       (this->DataExtent[3]-this->DataExtent[2]>=0) &&
316       (this->DataExtent[5]-this->DataExtent[4]>=0))
317    {
318       // The memory size for a full stack of images of course depends
319       // on the number of planes and the size of each image:
320       //size_t StackNumPixels = this->NumColumns * this->NumLines
321       //                      * this->TotalNumberOfPlanes * this->NumComponents;
322       //size_t stack_size = StackNumPixels * this->PixelSize; //not used
323       // Allocate pixel data space itself.
324
325       // Variables for the UpdateProgress. We shall use 50 steps to signify
326       // the advance of the process:
327       unsigned long UpdateProgressTarget = (unsigned long) ceil (this->NumLines
328                                          * this->TotalNumberOfPlanes
329                                          / 50.0);
330       // The actual advance measure:
331       unsigned long UpdateProgressCount = 0;
332
333       // Filling the allocated memory space with each image/volume:
334
335       size_t size = this->NumColumns * this->NumLines * this->NumPlanes
336                   * data->GetScalarSize() * this->NumComponents;
337       unsigned char *Dest = (unsigned char *)data->GetScalarPointer();
338       for (std::vector<gdcm::File* >::iterator it =  InternalFileList.begin();
339                                                it != InternalFileList.end();
340                                              ++it)
341       {
342          this->LoadImageInMemory(*it, Dest,
343                                  UpdateProgressTarget,
344                                  UpdateProgressCount); 
345          Dest += size;
346       }
347    }
348 }
349
350 /*
351  * vtkGdcmReader can have the file names specified through two ways:
352  * (1) by calling the vtkImageReader2::SetFileName(), SetFilePrefix() and
353  *     SetFilePattern()
354  * (2) By successive calls to vtkGdcmReader::AddFileName()
355  * When the first method was used by caller we need to update the local
356  * filename list
357  */
358 void vtkGdcmReader::BuildFileListFromPattern()
359 {
360    this->RemoveAllInternalFileName();
361
362    // Test miscellanous cases
363    if ((! this->FileNameList.empty()) && this->FileName )
364    {
365       vtkErrorMacro(<< "Both AddFileName and SetFileName schemes were used");
366       vtkErrorMacro(<< "No images loaded ! ");
367       return;
368    }
369
370    if ((! this->FileNameList.empty()) && this->FilePrefix )
371    {
372       vtkErrorMacro(<< "Both AddFileName and SetFilePrefix schemes were used");
373       vtkErrorMacro(<< "No images loaded ! ");
374       return;
375    }
376
377    if (this->FileName && this->FilePrefix)
378    {
379       vtkErrorMacro(<< "Both SetFileName and SetFilePrefix schemes were used");
380       vtkErrorMacro(<< "No images loaded ! ");
381       return;
382    }
383
384    // Create the InternalFileNameList
385    if (! this->FileNameList.empty()  )
386    {
387       vtkDebugMacro(<< "Using the AddFileName specified files");
388       this->InternalFileNameList=this->FileNameList;
389       return;
390    }
391
392    if (!this->FileName && !this->FilePrefix)
393    {
394       vtkErrorMacro(<< "FileNames are not set. Either use AddFileName() or");
395       vtkErrorMacro(<< "specify a FileName or FilePrefix.");
396       return;
397    }
398
399    if( this->FileName )
400    {
401       // Single file loading (as given with ::SetFileName()):
402       // Case of multi-frame file considered here
403       this->ComputeInternalFileName(this->DataExtent[4]);
404       vtkDebugMacro(<< "Adding file " << this->InternalFileName);
405       this->AddInternalFileName(this->InternalFileName);
406    }
407    else
408    {
409       // Multi file loading (as given with ::SetFilePattern()):
410       for (int idx = this->DataExtent[4]; idx <= this->DataExtent[5]; ++idx)
411       {
412          this->ComputeInternalFileName(idx);
413          vtkDebugMacro(<< "Adding file " << this->InternalFileName);
414          this->AddInternalFileName(this->InternalFileName);
415       }
416    }
417 }
418
419 /**
420  * Load all the files and set it in the InternalFileList
421  * For each file, the readability and the coherence of image caracteristics 
422  * are tested. If an image doesn't agree the required specifications, it
423  * isn't considered and no data will be set for the planes corresponding
424  * to this image
425  *
426  * The source of this work is the list of file name generated by the
427  * BuildFileListFromPattern method
428  */
429 void vtkGdcmReader::LoadFileInformation()
430 {
431    gdcm::File *file;
432    bool foundReference=false;
433    std::string type;
434
435    this->OwnFile=true;
436    for (std::list<std::string>::iterator filename = InternalFileNameList.begin();
437         filename != InternalFileNameList.end();
438         ++filename)
439    {
440       // check for file readability
441       FILE *fp;
442       fp = fopen(filename->c_str(),"rb");
443       if (!fp)
444       {
445          vtkErrorMacro(<< "Unable to open file " << filename->c_str());
446          vtkErrorMacro(<< "Removing this file from read files: "
447                        << filename->c_str());
448          file = NULL;
449          InternalFileList.push_back(file);
450          continue;
451       }
452       fclose(fp);
453
454       // Read the file
455       file=new gdcm::File();
456       file->SetLoadMode( LoadMode );
457       file->SetFileName(filename->c_str() );
458       file->Load();
459
460       // Test the Dicom file readability
461       if(!file->IsReadable())
462       {
463          vtkErrorMacro(<< "Gdcm cannot parse file " << filename->c_str());
464          vtkErrorMacro(<< "Removing this file from read files: "
465                         << filename->c_str());
466          delete file;
467          file=NULL;
468          InternalFileList.push_back(file);
469          continue;
470       }
471
472       // Test the Pixel Type recognition
473       type = file->GetPixelType();
474       if (   (type !=  "8U") && (type !=  "8S")
475           && (type != "16U") && (type != "16S")
476           && (type != "32U") && (type != "32S") )
477       {
478          vtkErrorMacro(<< "Bad File Type for file " << filename->c_str() << "\n"
479                        << "   File type found : " << type.c_str() 
480                        << " (might be 8U, 8S, 16U, 16S, 32U, 32S) \n"
481                        << "   Removing this file from read files");
482          delete file;
483          file=NULL;
484          InternalFileList.push_back(file);
485          continue;
486       }
487
488       // Test the image informations
489       if(!foundReference)
490       {
491          foundReference = true;
492          GetFileInformation(file);
493
494          vtkDebugMacro(<< "This file taken as coherence reference:"
495                         << filename->c_str());
496          vtkDebugMacro(<< "Image dimensions of reference file as read from Gdcm:" 
497                         << this->NumColumns << " " << this->NumLines << " " 
498                         << this->NumPlanes);
499       }
500       else if(!TestFileInformation(file))
501       {
502          delete file;
503          file=NULL;
504       }
505
506       InternalFileList.push_back(file);
507    }
508 }
509
510 /**
511  * Update the file informations.
512  * This works exactly like LoadFileInformation, but the source of work
513  * is the list of coherent files
514  */
515 void vtkGdcmReader::UpdateFileInformation()
516 {
517    this->InternalFileList=*(this->CoherentFileList);
518    this->OwnFile=false;
519
520    for(gdcmFileList::iterator it=InternalFileList.begin();
521                               it!=InternalFileList.end();
522                               ++it)
523    {
524       if( *it != NULL)
525       {
526          GetFileInformation(*it);
527          break;
528       }
529    }
530 }
531
532 /**
533  * Get the informations from a file.
534  * These informations are required to specify the output image
535  * caracteristics
536  */
537 void vtkGdcmReader::GetFileInformation(gdcm::File *file)
538 {
539    // Get the image caracteristics
540    this->NumColumns = file->GetXSize();
541    this->NumLines   = file->GetYSize();
542    this->NumPlanes  = file->GetZSize();
543
544    if (CoherentFileList == 0)
545       this->TotalNumberOfPlanes = this->NumPlanes*InternalFileNameList.size();
546    else
547       this->TotalNumberOfPlanes = this->NumPlanes*CoherentFileList->size();
548
549    this->ImageType = file->GetPixelType();
550    this->PixelSize = file->GetPixelSize();
551
552    this->DataSpacing[0] = file->GetXSpacing();
553    this->DataSpacing[1] = file->GetYSpacing();
554    this->DataSpacing[2] = file->GetZSpacing();
555
556    // Get the image data caracteristics
557    if( file->HasLUT() && this->AllowLookupTable )
558    {
559       // I could raise an error is AllowLookupTable is on and HasLUT() off
560       this->NumComponents = file->GetNumberOfScalarComponentsRaw();
561    }
562    else
563    {
564       this->NumComponents = file->GetNumberOfScalarComponents(); //rgb or mono
565    }
566 }
567
568 /*
569  * When more than one filename is specified (i.e. we expect loading
570  * a stack or volume) we need to check that the corresponding images/volumes
571  * to be loaded are coherent i.e. to make sure:
572  *     - they all share the same X dimensions
573  *     - they all share the same Y dimensions
574  *     - they all share the same ImageType ( 8 bit signed, or unsigned...)
575  *
576  * Eventually, we emit a warning when all the files do NOT share the
577  * Z dimension, since we can still build a stack but the
578  * files are not coherent in Z, which is probably a source a trouble...
579  *   When files are not readable (either the file cannot be opened or
580  * because gdcm cannot parse it), they are flagged as "GDCM_UNREADABLE".  
581  *   This method returns the total number of planar images to be loaded
582  * (i.e. an image represents one plane, but a volume represents many planes)
583  */
584 /**
585  * Test the coherent informations of the file with the reference informations
586  * used as image caracteristics. The tested informations are :
587  * - they all share the same X dimensions
588  * - they all share the same Y dimensions
589  * - they all share the same Z dimensions
590  * - they all share the same number of components
591  * - they all share the same ImageType ( 8 bit signed, or unsigned...)
592  *
593  * \return True if the file match, False otherwise
594  */
595 bool vtkGdcmReader::TestFileInformation(gdcm::File *file)
596 {
597    int numColumns = file->GetXSize();
598    int numLines   = file->GetYSize();
599    int numPlanes  = file->GetZSize();
600    int numComponents;
601    unsigned int pixelSize  = file->GetPixelSize();
602
603    if( file->HasLUT() && this->AllowLookupTable )
604       numComponents = file->GetNumberOfScalarComponentsRaw();
605    else
606       numComponents = file->GetNumberOfScalarComponents(); //rgb or mono
607
608    if( numColumns != this->NumColumns )
609    {
610       vtkErrorMacro(<< "File X value doesn't match with the previous ones: "
611                     << file->GetFileName().c_str()
612                     << ". Found " << numColumns << ", must be "
613                     << this->NumColumns);
614       return false;
615    }
616    if( numLines != this->NumLines )
617    {
618       vtkErrorMacro(<< "File Y value doesn't match with the previous ones: "
619                     << file->GetFileName().c_str()
620                     << ". Found " << numLines << ", must be "
621                     << this->NumLines);
622       return false;
623    }
624    if( numPlanes != this->NumPlanes )
625    {
626       vtkErrorMacro(<< "File Z value doesn't match with the previous ones: "
627                     << file->GetFileName().c_str()
628                     << ". Found " << numPlanes << ", must be "
629                     << this->NumPlanes);
630       return false;
631    }
632    if( numComponents != this->NumComponents )
633    {
634       vtkErrorMacro(<< "File Components count doesn't match with the previous ones: "
635                     << file->GetFileName().c_str()
636                     << ". Found " << numComponents << ", must be "
637                     << this->NumComponents);
638       return false;
639    }
640    if( pixelSize != this->PixelSize )
641    {
642       vtkErrorMacro(<< "File pixel size doesn't match with the previous ones: "
643                     << file->GetFileName().c_str()
644                     << ". Found " << pixelSize << ", must be "
645                     << this->PixelSize);
646       return false;
647    }
648
649    return true;
650 }
651
652 //-----------------------------------------------------------------------------
653 // Private
654 /*
655  * Remove all file names to the internal list of images to read.
656  */
657 void vtkGdcmReader::RemoveAllInternalFileName(void)
658 {
659    this->InternalFileNameList.clear();
660 }
661
662 /*
663  * Adds a file name to the internal list of images to read.
664  */
665 void vtkGdcmReader::AddInternalFileName(const char *name)
666 {
667    char *LocalName = new char[strlen(name) + 1];
668    strcpy(LocalName, name);
669    this->InternalFileNameList.push_back(LocalName);
670    delete[] LocalName;
671 }
672
673 /*
674  * Remove all file names to the internal list of images to read.
675  */
676 void vtkGdcmReader::RemoveAllInternalFile(void)
677 {
678    if(this->OwnFile)
679    {
680       for(gdcmFileList::iterator it=InternalFileList.begin();
681                                  it!=InternalFileList.end();
682                                  ++it)
683       {
684          delete (*it);
685       }
686    }
687    this->InternalFileList.clear();
688 }
689
690 void vtkGdcmReader::IncrementProgress(const unsigned long updateProgressTarget,
691                                       unsigned long &updateProgressCount)
692 {
693    // Update progress related for bad files:
694    updateProgressCount += this->NumLines;
695    if (updateProgressTarget > 0)
696    {
697       if (!(updateProgressCount%updateProgressTarget))
698       {
699          this->UpdateProgress(updateProgressCount/(50.0*updateProgressTarget));
700       }
701    }
702 }
703
704 /*
705  * Loads the contents of the image/volume contained by char *fileName at
706  * the dest memory address. Returns the size of the data loaded.
707  */
708 /*void vtkGdcmReader::LoadImageInMemory(
709              std::string fileName, 
710              unsigned char *dest,
711              const unsigned long updateProgressTarget,
712              unsigned long &updateProgressCount)
713 {
714    vtkDebugMacro(<< "Copying to memory image [" << fileName.c_str() << "]");
715
716    gdcm::File *f;
717    f = new gdcm::File();
718    f->SetLoadMode( LoadMode );
719    f->SetFileName( fileName.c_str() );
720    f->Load( );
721
722    LoadImageInMemory(f,dest,
723                      updateProgressTarget,
724                      updateProgressCount);
725    delete f;
726 }*/
727
728 /*
729  * Loads the contents of the image/volume contained by gdcm::File* f at
730  * the Dest memory address. Returns the size of the data loaded.
731  * \ param f File to consider. NULL if the file must be skiped
732  * \remarks Assume that if (f != NULL) then its caracteristics match
733  * with the previous ones
734  */
735 void vtkGdcmReader::LoadImageInMemory(
736              gdcm::File *f, 
737              unsigned char *dest,
738              const unsigned long updateProgressTarget,
739              unsigned long &updateProgressCount)
740 {
741    if(!f)
742       return;
743
744    gdcm::FileHelper *fileH = new gdcm::FileHelper( f );
745    fileH->SetUserFunction( UserFunction );
746
747    int numColumns = f->GetXSize();
748    int numLines   = f->GetYSize();
749    int numPlanes  = f->GetZSize();
750    int numComponents;
751
752    if( f->HasLUT() && this->AllowLookupTable )
753       numComponents = f->GetNumberOfScalarComponentsRaw();
754    else
755       numComponents = f->GetNumberOfScalarComponents(); //rgb or mono
756    vtkDebugMacro(<< "numComponents:" << numComponents);
757    vtkDebugMacro(<< "Copying to memory image [" << f->GetFileName().c_str() << "]");
758    //size_t size;
759
760    // If the data structure of vtk for image/volume representation
761    // were straigthforwards the following would be enough:
762    //    GdcmFile.GetImageDataIntoVector((void*)Dest, size);
763    // But vtk chooses to invert the lines of an image, that is the last
764    // line comes first (for some axis related reasons?). Hence we need
765    // to load the image line by line, starting from the end.
766
767    int lineSize   = NumComponents * numColumns * f->GetPixelSize();
768    int planeSize  = lineSize * numLines;
769
770    unsigned char *src;
771    
772    if( fileH->GetFile()->HasLUT() && AllowLookupTable )
773    {
774       // to avoid bcc 5.5 w
775       /*size               = */ fileH->GetImageDataSize(); 
776       src                = (unsigned char*) fileH->GetImageDataRaw();
777       unsigned char *lut = (unsigned char*) fileH->GetLutRGBA();
778
779       if(!this->LookupTable)
780       {
781          this->LookupTable = vtkLookupTable::New();
782       }
783
784       this->LookupTable->SetNumberOfTableValues(256);
785       for (int tmp=0; tmp<256; tmp++)
786       {
787          this->LookupTable->SetTableValue(tmp,
788          (float)lut[4*tmp+0]/255.0,
789          (float)lut[4*tmp+1]/255.0,
790          (float)lut[4*tmp+2]/255.0,
791          1);
792       }
793       this->LookupTable->SetRange(0,255);
794       vtkDataSetAttributes *a = this->GetOutput()->GetPointData();
795       a->GetScalars()->SetLookupTable(this->LookupTable);
796       free(lut);
797    }
798    else
799    {
800       //size = fileH->GetImageDataSize(); 
801       // useless - just an accessor;  'size' unused
802       src  = (unsigned char*)fileH->GetImageData();  
803    } 
804
805    unsigned char *dst = dest + planeSize - lineSize;
806    for (int plane = 0; plane < numPlanes; plane++)
807    {
808       for (int line = 0; line < numLines; line++)
809       {
810          // Copy one line at proper destination:
811          memcpy((void*)dst, (void*)src, lineSize);
812          src += lineSize;
813          dst -= lineSize;
814          // Update progress related:
815          if (!(updateProgressCount%updateProgressTarget))
816          {
817             this->UpdateProgress(updateProgressCount/(50.0*updateProgressTarget));
818          }
819          updateProgressCount++;
820       }
821       dst += 2 * planeSize;
822    }
823
824    delete fileH;
825 }
826
827 //-----------------------------------------------------------------------------