]> Creatis software - gdcm.git/blob - Example/ToInTag.cxx
Avoid confusion due to missing values
[gdcm.git] / Example / ToInTag.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: ToInTag.cxx,v $
5   Language:  C++
6   Date:      $Date: 2007/07/04 15:40:51 $
7   Version:   $Revision: 1.16 $
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 #include "gdcmDocEntry.h"
19 #include "gdcmDicomDir.h"
20 #include "gdcmDicomDirPatient.h"
21 #include "gdcmFile.h"
22 #include "gdcmFileHelper.h"
23 #include "gdcmDirList.h"
24 #include "gdcmDebug.h"
25 #include "gdcmArgMgr.h"
26 #include "gdcmUtil.h"
27 #include "gdcmSerieHelper.h"
28
29 #include <iostream>
30
31 /**
32   * \brief   
33   *          - explores recursively the given directory
34   *          - keeps the requested series
35   *          - orders the gdcm-readable found Files
36   *            according to their Patient/Study/Serie/Image characteristics
37   *          - fills a single level Directory with *all* the files,
38   *            converted into a Brucker-like Dicom, Intags compliant
39   */  
40
41 typedef std::map<std::string, GDCM_NAME_SPACE::File*> SortedFiles;
42
43 int main(int argc, char *argv[]) 
44 {
45    START_USAGE(usage)
46    " \n ToInTag :\n                                                           ",
47    " - explores recursively the given directory,                              ",
48    " - keeps the requested series/ drops the unrequested series               ",
49    " - orders the gdcm-readable found Files according to their                ",
50    "           (0x0010, 0x0010) Patient's Name                                ",
51    "           (0x0020, 0x000e) Series Instance UID                           ",
52    "           (0x0020, 0x0032) Image Position (Patient)                      ",
53    "           (0x0018, 0x1060) Trigger Time                                  ",
54    "           (0x0018, 0x1312) In-plane Phase Encoding Direction             ",
55    " - fills a single level (*) Directory with *all* the files,               ",
56    "           converted into a Brucker-like Dicom, InTags compliant          ",
57    "   (*) actually : creates as many directories as Patients                 ",
58    "                  -that shouldn't appear, but being carefull is better!-  ",
59    " or                                                                       ",
60    " - fills a tree-like structure of directories as :                        ",
61    "        - Patient                                                         ",
62    "        -- Serie                                                          ",
63    "        --- Position                                                      ",
64    "        ---- Images (sorted by Trigger Time /                             ",
65    "                               Encoding Direction (Row, Column)           ",
66    "                                                                          ",
67    "      Note : when (0008|1090) [Model Name ] equals 'TrioTim ' :           ",
68    "         - (0008|103e)[Series Description ] is checked for                ",
69    "            '90' (-> COL) or '0' (-> ROW)                                 ",
70    "         - (0x0020, 0x000e) [Series Instance UID] is NOT dealt with,      ",
71    "           since row an col tagging are in 2 different Series             ",
72    "           DO NOT supply a directory holding different exams              ",
73    "           for the same Slice level!                                      ",
74    "      uses :                                                              ",
75    "           0x0021, 0x1020 : 'SLICE INDEX'                                 ",
76    "           0x0021, 0x1040 : 'FRAME INDEX'                                 ",
77    "           0x0020, 0x0012 : 'SESSION INDEX'  (Acquisition Number)         ",
78    "                                                                          ",
79    " usage:                                                                   ",
80    " -----                                                                    ",
81    " ToInTag          dirin=rootDirectoryName                                 ",
82    "                  dirout=outputDirectoryName                              ",
83    "                  {  [keep= list of seriesNumber to process]              ",
84    "                   | [drop= list of seriesNumber to ignore] }             ",
85    "                  [taggrid] [skel]                                        ",
86    "                  [input = {ACR|DCM}]                                     ", 
87    "                  [extent=image suffix (.IMA, .NEMA, .DCM, ...)]          ",
88    "                  [listonly] [split] [rubout]                             ",
89    "                  [noshadowseq][noshadow][noseq] [verbose] [debug]        ",
90    "                                                                          ",
91    " dirout : will be created if doesn't exist                                ",
92    " keep : if user wants to process a limited number of series               ",
93    "            he gives the list of 'SeriesNumber' (tag 0020|0011)           ",
94    " drop : if user wants to ignore a limited number of series                ",
95    "            he gives the list of 'SeriesNumber' (tag 0020|0011)           ",   
96    "        SeriesNumber are short enough to be human readable                ",
97    "        e.g : 1030,1035,1043                                              ", 
98    " taggrid : user knows all the images are 'grid' -ie: not 'col', not 'raw'-",
99    " extent : DO NOT forget the leading '.' !                                 ",
100    " skel: name skeleton eg : patName_1.nema -> skel=patName_                 ",
101    " split: creates a tree-like structure of directories as :                 ",
102    "        - Patient                                                         ",
103    "        -- Serie                                                          ",
104    "        --- Position                                                      ",
105    "        ---- Images (sorted by Trigger Time /                             ",
106    "                               Encoding Direction (Row, Column)           ",
107    " rubout : user asks to rubout burnt-in image number                       ",
108    " noshadowseq: user doesn't want to load Private Sequences                 ",
109    " noshadow : user doesn't want to load Private groups (odd number)         ",
110    " noseq    : user doesn't want to load Sequences                           ",
111    " verbose  : user wants to run the program in 'verbose mode'               ",
112    " debug    : *developer*  wants to run the program in 'debug mode'         ",
113    FINISH_USAGE
114
115    std::cout << "inside ToInTag" << std::endl;
116    
117    // ----- Initialize Arguments Manager ------
118       
119    GDCM_NAME_SPACE::ArgMgr *am = new GDCM_NAME_SPACE::ArgMgr(argc, argv);
120   
121    if (argc == 1 || am->ArgMgrDefined("usage")) 
122    {
123       am->ArgMgrUsage(usage); // Display 'usage'
124       delete am;
125       return 0;
126    }
127
128    const char *dirNamein;   
129    dirNamein  = am->ArgMgrGetString("dirin","."); 
130
131    const char *dirNameout;   
132    dirNameout  = am->ArgMgrGetString("dirout",".");  
133    
134    int loadMode = GDCM_NAME_SPACE::LD_ALL;
135    if ( am->ArgMgrDefined("noshadowseq") )
136       loadMode |= GDCM_NAME_SPACE::LD_NOSHADOWSEQ;
137    else 
138    {
139    if ( am->ArgMgrDefined("noshadow") )
140          loadMode |= GDCM_NAME_SPACE::LD_NOSHADOW;
141       if ( am->ArgMgrDefined("noseq") )
142          loadMode |= GDCM_NAME_SPACE::LD_NOSEQ;
143    }
144
145    if (am->ArgMgrDefined("debug"))
146       GDCM_NAME_SPACE::Debug::DebugOn();
147       
148    int verbose  = am->ArgMgrDefined("verbose");
149    int split    = am->ArgMgrDefined("split");
150    int listonly = am->ArgMgrDefined("listonly");
151    
152    bool rubout = ( 0 != am->ArgMgrDefined("rubout") ); 
153            
154    int nbSeriesToKeep;
155    int *seriesToKeep = am->ArgMgrGetListOfInt("keep", &nbSeriesToKeep);
156    int nbSeriesToDrop;
157    int *seriesToDrop = am->ArgMgrGetListOfInt("drop", &nbSeriesToDrop);
158  
159    if ( nbSeriesToKeep!=0 && nbSeriesToDrop!=0)
160    {
161       std::cout << "KEEP and DROP are mutually exclusive !" << std::endl;
162       delete am;
163       return 0;         
164    }
165    
166    int taggrid = am->ArgMgrDefined("taggrid");
167    
168    int hasSkel = am->ArgMgrDefined("skel");
169    const char *skel;
170    if (hasSkel)
171       skel = am->ArgMgrGetString("skel");   
172       
173    const char *extent  = am->ArgMgrGetString("extent",".DCM");
174    
175    // if unused Param we give up
176    if ( am->ArgMgrPrintUnusedLabels() )
177    { 
178       am->ArgMgrUsage(usage);
179       delete am;
180       return 0;
181    }
182    delete am;  // we don't need Argument Manager any longer
183
184    // ----- Begin Processing -----
185    
186    if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(dirNamein) )
187    {
188       std::cout << "KO : [" << dirNamein << "] is not a Directory." << std::endl;
189       return 0;
190
191    }
192    else
193    {
194       std::cout << "OK : [" << dirNamein << "] is a Directory." << std::endl;
195    }
196
197    std::string systemCommand;
198    
199    std::cout << "Check for output directory :[" << dirNameout << "]."
200              <<std::endl;
201    if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(dirNameout) )    // dirout not found
202    {
203       std::string strDirNameout(dirNameout);          // to please gcc 4
204       systemCommand = "mkdir " +strDirNameout;        // create it!
205       if (verbose)
206          std::cout << systemCommand << std::endl;
207       system (systemCommand.c_str());
208       if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(dirNameout) ) // be sure it worked
209       {
210           std::cout << "KO : not a dir : [" << dirNameout << "] (creation failure ?)" << std::endl;
211       return 0;
212
213       }
214       else
215       {
216         std::cout << "Directory [" << dirNameout << "] created." << std::endl;
217       }
218    }
219    else
220    {
221        std::cout << "Output Directory [" << dirNameout << "] already exists; Used as is." << std::endl;
222    }
223     
224    std::string strDirNamein(dirNamein);
225    GDCM_NAME_SPACE::DirList dirList(strDirNamein, true); // get recursively the list of files
226    
227    if (listonly)
228    {
229       std::cout << "------------List of found files ------------" << std::endl;
230       dirList.Print();
231       std::cout << std::endl;
232    }
233    
234    GDCM_NAME_SPACE::DirListType fileNames;
235    fileNames = dirList.GetFilenames();
236    GDCM_NAME_SPACE::SerieHelper *s;              // Needed to use SerieHelper::AddSeriesDetail()
237    s = GDCM_NAME_SPACE::SerieHelper::New();
238
239    std::string token = "%%%"; // Hope it's enough!
240 /*       
241    std::cout << "---------------Print Serie--------------" << std::endl; 
242    s->SetDirectory(dirNamein, true); // true : recursive exploration 
243    s->SetUseSeriesDetails(true);  
244    s->AddSeriesDetail(0x0018, 0x1312);   
245    s->Print();
246 */
247   
248    GDCM_NAME_SPACE::File *f;
249    GDCM_NAME_SPACE::FileHelper *fh;
250    std::vector<std::string> tokens;
251    std::vector<std::string> tokensForFileName;
252    
253    // For Siemens pb, we need Manufacturer's Model Name
254    
255    GDCM_NAME_SPACE::DirListType::iterator it1 = fileNames.begin();
256    f = GDCM_NAME_SPACE::File::New();
257    f->SetLoadMode(GDCM_NAME_SPACE::LD_ALL);
258    f->SetFileName( *it1 );
259    f->Load();
260    std::string modelName = f->GetEntryString(0x0008,0x1090);
261    f->Delete();   
262    
263 /*   
264    std::cout << "---------------Print Unique Series identifiers---------"  
265              << std::endl;     
266    std::string uniqueSeriesIdentifier;
267  
268    for (GDCM_NAME_SPACE::DirListType::iterator it) = fileNames.begin();  
269                                     it != fileNames.end();
270                                   ++it)
271    {
272       std::cout << "File Name : " << *it << std::endl;
273       f = GDCM_NAME_SPACE::File::New();
274       f->SetLoadMode(GDCM_NAME_SPACE::LD_ALL);
275       f->SetFileName( *it );
276       f->Load();
277         
278       uniqueSeriesIdentifier=s->CreateUniqueSeriesIdentifier(f);
279       std::cout << "                           [" <<
280                uniqueSeriesIdentifier  << "]" << std::endl;       
281       f->Delete();
282    }
283 */
284    
285    if (verbose)
286       std::cout << "------------------Print Break levels-----------------" << std::endl;
287
288    std::string userFileIdentifier; 
289    SortedFiles sf;
290
291    s->AddSeriesDetail(0x0010, 0x0010, false); // Patient's Name
292    // for Siemens TrioTim, don't deal with 'Series Instance UID'
293    if ( !GDCM_NAME_SPACE::Util::DicomStringEqual(modelName,"TrioTim") ) 
294       s->AddSeriesDetail(0x0020, 0x000e, false); // Series Instance UID
295    else
296       s->AddSeriesDetail(0x9999, 0x9999, false); // dirty trick to ignore 'Series Instance UID'
297    s->AddSeriesDetail(0x0020, 0x0032, false); // Image Position (Patient)     
298    s->AddSeriesDetail(0x0018, 0x1060, true);  // Trigger Time (true: convert to keep numerical order)
299    s->AddSeriesDetail(0x0018, 0x1312, false); // In-plane Phase Encoding Direction 
300    s->AddSeriesDetail(0x0008, 0x103e, false); // Series Description (special Siemens ...)  
301
302    //uint8_t *imageData; // Useless : pixels will not be loaded 
303                          //          (images are overwritten)
304          
305    for (GDCM_NAME_SPACE::DirListType::iterator it = fileNames.begin();  
306                                     it != fileNames.end();
307                                   ++it)
308    {
309       f = GDCM_NAME_SPACE::File::New();
310       f->SetLoadMode(loadMode);
311       f->SetFileName( *it );
312       f->Load();
313
314       std::string strSeriesNumber;
315       int seriesNumber;
316       int j;
317
318       // keep only requested Series      
319       bool keep = false;
320       if (nbSeriesToKeep != 0)
321       {     
322          strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
323          seriesNumber = atoi( strSeriesNumber.c_str() );
324          for (j=0;j<nbSeriesToKeep; j++)
325          {
326             if(seriesNumber == seriesToKeep[j])
327             {
328                keep = true;
329                break;
330             }
331          }
332          if ( !keep)
333          {
334             f->Delete();
335             continue;
336          } 
337       }
338       // drop all unrequested Series
339       bool drop = false;
340       if (nbSeriesToDrop != 0)
341       {     
342          strSeriesNumber = f->GetEntryString(0x0020, 0x0011 );
343          seriesNumber = atoi( strSeriesNumber.c_str() );
344          for (j=0;j<nbSeriesToDrop; j++)
345          {
346             if(seriesNumber == seriesToDrop[j])
347             { 
348                drop = true;
349                break;
350             }
351         }
352         if (drop)
353         {
354            f->Delete();
355            continue;
356         }
357       } 
358
359       userFileIdentifier=s->CreateUserDefinedFileIdentifier(f); 
360       tokens.clear();
361       GDCM_NAME_SPACE::Util::Tokenize (userFileIdentifier, tokens, token); 
362    
363       int imageNum; // Within FileName
364       char newName[1024];
365       
366       if ( tokens[3] == GDCM_NAME_SPACE::GDCM_UNFOUND)  // sometimes Trigger Time is not found. CreateUserDefinedFileIdentifier is not aware of the pb.
367       {
368          ///this is a trick to build up a lexicographical compliant name :
369          ///     eg : fich001.ima vs fich100.ima as opposed to fich1.ima vs fich100.ima
370          std::string name = GDCM_NAME_SPACE::Util::GetName( *it );
371          if (hasSkel)
372          {
373             GDCM_NAME_SPACE::Util::Tokenize (name, tokensForFileName, skel);
374             imageNum = atoi ( tokensForFileName[0].c_str() );
375             // probabely we could write something much more complicated using C++ !
376             sprintf (newName, "%s%06d%s", skel, imageNum, extent);
377             tokens[3] = newName;
378             tokensForFileName.clear();    
379          }
380          else
381             tokens[3] = name;
382  
383  
384          userFileIdentifier = tokens[0] + token + tokens[1] + token + tokens[2] + token 
385                     + tokens[3] + token + tokens[4] + token + tokens[5] + token;
386       }   
387       if (verbose) 
388          std::cout << "[" << userFileIdentifier  << "] : " << *it << std::endl;
389                
390       // storing in a map ensures automatic sorting !      
391       sf[userFileIdentifier] = f;
392    }
393    
394    if (verbose)
395       std::cout << "  " << std::endl;
396       
397    std::string fullFilename, lastFilename;
398    std::string previousPatientName, currentPatientName;
399    std::string previousSerieInstanceUID, currentSerieInstanceUID;
400    std::string previousImagePosition, currentImagePosition;
401    std::string previousPhaseEncodingDirection, currentPhaseEncodingDirection;
402    std::string previousTriggerTime, currentTriggerTime;
403    
404    std::string currentStudyUID;
405    std::string seriesDescription;  
406       
407    std::string writeDir, currentWriteDir;
408    std::string currentPatientWriteDir, currentSerieWriteDir, 
409                currentPositionWriteDir, currentPhaseEncodingDirectionWriteDir;
410
411    std::string fullWriteFilename;
412    std::string strExtent(extent); 
413            
414    writeDir = GDCM_NAME_SPACE::Util::NormalizePath(dirNameout);     
415    SortedFiles::iterator it2;
416  
417    previousPatientName            = "";
418    previousSerieInstanceUID       = "";   
419    previousImagePosition          = "";
420    previousPhaseEncodingDirection = "";
421    previousTriggerTime            = "";
422    
423    int sliceIndex = 0; // Is incremented *at the beginning* of processing
424    int frameIndex;
425    if (taggrid)
426        frameIndex = 0;
427    else
428        frameIndex = 1;
429       
430    int flag       = 0;
431        
432    GDCM_NAME_SPACE::File *currentFile;
433
434    std::string defaultStudyUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID();
435    std::string defaultSerieUID;
436      
437    for (it2 = sf.begin() ; it2 != sf.end(); ++it2)
438    {  
439       currentFile = it2->second;
440        
441       fullFilename =  currentFile->GetFileName();
442       lastFilename =  GDCM_NAME_SPACE::Util::GetName( fullFilename );
443       if (verbose) 
444       std::cout <<" ------------------------------------------------------------------------------" 
445                 << std::endl << " Deal with [" << it2->first << "] : ["<<fullFilename << "]" 
446                 << std::endl;
447      
448       tokens.clear();
449       GDCM_NAME_SPACE::Util::Tokenize (it2->first, tokens, token);
450       
451       currentPatientName            = tokens[0];
452       currentSerieInstanceUID       = tokens[1];
453       currentImagePosition          = tokens[2];
454       currentTriggerTime            = tokens[3];
455       currentPhaseEncodingDirection = tokens[4];
456       seriesDescription             = tokens[5];  // For Siemens pb
457
458       if ( currentImagePosition[0] == '-')
459           currentImagePosition[0] = 'M';
460       if ( currentImagePosition[0] == '+')
461           currentImagePosition[0] = 'P'; 
462
463       // Add a default ImagePositionPatient to avoid confusion at post processing time
464       if ( currentFile->GetEntryString(0x0020,0x0032) == GDCM_NAME_SPACE::GDCM_UNFOUND && 
465            currentFile->GetEntryString(0x0020,0x0030) == GDCM_NAME_SPACE::GDCM_UNFOUND )
466       {
467          currentFile->InsertEntryString("0.\\0.\\0.",0x0020, 0x0032, "DS" );
468       }
469
470       // Add a default ImagePositionPatient to avoid confusion at post processing time
471       if ( currentFile->GetEntryString(0x0020,0x0037) == GDCM_NAME_SPACE::GDCM_UNFOUND && 
472            currentFile->GetEntryString(0x0020,0x0035) == GDCM_NAME_SPACE::GDCM_UNFOUND )
473       {
474          currentFile->InsertEntryString("1.\\0.\\0.\\0.\\1.\\0.",0x0020, 0x0037, "DS" );
475       }
476       
477       if (previousPatientName != currentPatientName)
478       {      
479          if ( currentFile->GetEntryString(0x0020,0x000d) == GDCM_NAME_SPACE::GDCM_UNFOUND)
480          {
481             if (verbose)   
482                std::cout << "--- new  Study UID created" << std::endl;
483             defaultStudyUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID();
484             currentFile->InsertEntryString(defaultStudyUID, 0x0020, 0x000d, "UI" );
485          }
486   
487          previousPatientName = currentPatientName;
488          if (verbose)   
489             std::cout << "==== new Patient  [" << currentPatientName  << "]" << std::endl;
490     
491          previousPatientName            = currentPatientName;
492          previousSerieInstanceUID       = ""; //currentSerieInstanceUID;
493          previousImagePosition          = ""; //currentImagePosition;
494          previousTriggerTime            = "";
495          previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
496   
497          currentPatientWriteDir = writeDir + currentPatientName;
498          //if ( ! GDCM_NAME_SPACE::DirList::IsDirectory(currentPatientWriteDir) )
499            {
500               systemCommand   = "mkdir " + currentPatientWriteDir;
501               if (verbose)
502                  std::cout << systemCommand << std::endl;
503               system ( systemCommand.c_str() );
504          }
505       }
506
507       if ( GDCM_NAME_SPACE::Util::DicomStringEqual(modelName,"TrioTim") ) // for Siemens TrioTim , don't deal with 'Series Instance UID'
508
509       if (previousSerieInstanceUID != currentSerieInstanceUID)
510       {        
511          if (verbose)   
512             std::cout << "==== === new Serie [" << currentSerieInstanceUID << "]"
513                       << std::endl;
514       
515          if ( currentFile->GetEntryString(0x0020,0x000e) == GDCM_NAME_SPACE::GDCM_UNFOUND)
516          {
517             if (verbose)   
518                std::cout << "--- --- new  Serie UID created" << std::endl;
519             defaultSerieUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID();
520             currentFile->InsertEntryString(defaultSerieUID, 0x0020, 0x000e, "UI" );
521          }       
522       
523          if (split)
524          {
525              currentSerieWriteDir  = currentPatientWriteDir + GDCM_NAME_SPACE::GDCM_FILESEPARATOR
526                              + currentSerieInstanceUID;
527              systemCommand   = "mkdir " + currentSerieWriteDir;  
528              system (systemCommand.c_str());
529          }
530          previousSerieInstanceUID       = currentSerieInstanceUID;
531          previousImagePosition          = ""; //currentImagePosition;
532          previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
533       }
534       // end of modelName != "TrioTim "
535    
536       if (previousImagePosition != currentImagePosition)
537       {
538          frameIndex = 1;
539          flag = 0;        
540          if (verbose)   
541             std::cout << "=== === === new Position [" << currentImagePosition  << "]"
542                       << std::endl;
543          if (split)
544          {
545              currentPositionWriteDir  = currentSerieWriteDir + GDCM_NAME_SPACE::GDCM_FILESEPARATOR
546                              + currentImagePosition;
547              systemCommand   = "mkdir " + currentPositionWriteDir;     
548              system (systemCommand.c_str()); 
549          }
550          previousImagePosition          = currentImagePosition;
551          previousPhaseEncodingDirection = ""; //currentPhaseEncodingDirection;
552          if (split)
553             sliceIndex = 1; // only *one* slice in a given directory
554          else
555             sliceIndex += 1;
556       }
557
558 // We don't split on Row/Column!
559 /*
560       if (previousPhaseEncodingDirection != currentPhaseEncodingDirection)
561       {        
562          if (verbose)   
563             std::cout << "==== === === === new PhaseEncodingDirection [" 
564                       << currentPhaseEncodingDirection  << "]" << std::endl;
565       
566          if (split)
567          {
568              currentPhaseEncodingDirectionWriteDir  = currentPositionWriteDir 
569                              + GDCM_NAME_SPACE::GDCM_FILESEPARATOR
570                              + currentPhaseEncodingDirection;
571              systemCommand   = "mkdir " + currentPhaseEncodingDirectionWriteDir;     
572              system (systemCommand.c_str());     
573          }      
574     
575          previousPhaseEncodingDirection = currentPhaseEncodingDirection;
576       } 
577 */    
578    
579       if ( GDCM_NAME_SPACE::Debug::GetDebugFlag())
580          std::cout << "--- --- --- --- --- " << it2->first << "  " 
581                    << (it2->second)->GetFileName() << " " 
582                    << GDCM_NAME_SPACE::Util::GetName( fullFilename ) << std::endl;           
583       
584       // Transform the image to be 'Brucker-Like'
585       // ----------------------------------------   
586     
587       // Deal with 0x0019, 0x1000 : 'FOV'
588       int nX = currentFile->GetXSize();
589       int nY = currentFile->GetYSize();
590       float pxSzX = currentFile->GetXSpacing();
591       float pxSzY = currentFile->GetYSpacing();
592       char fov[64];
593       sprintf(fov, "%f\\%f",nX*pxSzX, nY*pxSzY);
594       if (currentFile->IsVRCoherent(0x0019) == 1 )
595          currentFile->InsertEntryString(fov, 0x0019, 0x1000, "  ");
596       else     
597          currentFile->InsertEntryString(fov, 0x0019, 0x1000, "DS");
598
599      
600       // Deal with 0x0020, 0x0012 : 'SESSION INDEX'  (Acquisition Number)
601       std::string chSessionIndex;
602       // CLEANME
603
604       if (taggrid)
605       { 
606          chSessionIndex = "1";
607       }
608       else
609       {
610       /* for SIEMENS MRI :
611         D 0008|1090 [LO] [Manufacturer's Model Name ] [Triotim ]
612         we have to deal with :
613      
614         D 0008|103e [LO]  [Series Description ] [fl2d9_line PA 15 90deg] or anything that contains '90' !
615         D 0008|103e [LO]  [Series Description ] [fl2d9_line PA 15 0deg ]
616         (everything is flagged as 'ROW')
617       */  
618
619          if ( GDCM_NAME_SPACE::Util::DicomStringEqual(modelName,"TrioTim") )  
620          {
621             if (seriesDescription.find("90", 0) != std::string::npos)
622                chSessionIndex = "1";  // 90 deg -> COL
623             else if (seriesDescription.find("0", 0)!= std::string::npos)
624                chSessionIndex = "2";  // 0 deg -> ROW
625             else
626             {
627                std::cout << "====================== seriesDescription doesn't contain"
628                          << " neither '90' nor '0' (?!?) : ["
629                          << seriesDescription << "]" << std::endl;
630                chSessionIndex = "1";
631             }    
632          } 
633          else  // for all other 'normal' cases
634          {
635             if (currentPhaseEncodingDirection == "COL" || currentPhaseEncodingDirection == "COL " || currentPhaseEncodingDirection == " COL")
636                chSessionIndex = "1";
637             else if (currentPhaseEncodingDirection == "ROW" || currentPhaseEncodingDirection == "ROW "|| currentPhaseEncodingDirection == " ROW")
638                chSessionIndex = "2"; 
639             else
640             {
641                std::cout << "====================== PhaseEncodingDirection "
642                          << " neither COL nor ROW (?!?) : [ "
643                          << currentPhaseEncodingDirection << "]" << std::endl;
644                chSessionIndex = "1";
645             }
646          }
647       }
648       
649       if (currentFile->IsVRCoherent(0x0020) == 1 )     
650          currentFile->InsertEntryString(chSessionIndex, 0x0020, 0x0012, "  ");
651       else
652          currentFile->InsertEntryString(chSessionIndex, 0x0020, 0x0012, "IS");
653  
654       // Deal with  0x0021, 0x1020 : 'SLICE INDEX'
655       char chSliceIndex[5];
656       sprintf(chSliceIndex, "%04d", sliceIndex);
657       std::string strChSliceIndex(chSliceIndex);
658        
659       // Deal with  0x0021, 0x1040 : 'FRAME INDEX' 
660       char chFrameIndex[5];
661       sprintf(chFrameIndex, "%04d", frameIndex);
662
663       std::string stringVR;       
664       if (currentFile->IsVRCoherent(0x0021) == 1 )
665          stringVR = "  ";
666       else
667         stringVR = "IS";
668   
669       currentFile->InsertEntryString(strChSliceIndex, 0x0021, 0x1020, stringVR);
670       currentFile->InsertEntryString(chFrameIndex,    0x0021, 0x1040, stringVR);
671       
672       if (verbose) {     
673          std::cout << "0x0021, 0x1020 : strChSliceIndex " << strChSliceIndex << std::endl;
674          std::cout << "0x0021, 0x1040 : chFrameIndex  "   << chFrameIndex    << std::endl; 
675          std::cout << "0x0020, 0x0012 : chSessionIndex "  << chSessionIndex  << std::endl; 
676       }
677         
678       std::string strImagePositionPatient    = currentFile->GetEntryString(0x0020, 0x0032 );
679       if (strImagePositionPatient == GDCM_NAME_SPACE::GDCM_UNFOUND)
680       {
681          if (verbose)
682             std::cout << "Duplicate ImagePosition into ImagePositionPatient" << std::endl;
683          currentFile->InsertEntryString(currentFile->GetEntryString(0x0020, 0x0030), 0x0020, 0x0032, "DS" );
684       }  
685       
686       std::string strImageOrientationPatient = f->GetEntryString(0x0020, 0x0037 );
687       if (strImageOrientationPatient == GDCM_NAME_SPACE::GDCM_UNFOUND)
688       {
689          if (verbose)
690             std::cout << "Duplicate ImageOrientation into ImageOrientationPatient" << std::endl;          
691          currentFile->InsertEntryString(currentFile->GetEntryString(0x0020, 0x0035), 0x0020, 0x0037, "DS" );       
692       }
693                 
694       if (taggrid)
695          frameIndex++;
696       else     
697       {     
698          if (flag == 0)
699          {       
700             flag = 1;
701          }
702          else
703          {
704             frameIndex++;
705             flag = 0;
706          }
707       } 
708                  
709       if (split)
710       
711          //fullWriteFilename = currentPhaseEncodingDirectionWriteDir + GDCM_NAME_SPACE::GDCM_FILESEPARATOR 
712          //                                + lastFilename + strExtent;      
713          fullWriteFilename = currentPositionWriteDir + GDCM_NAME_SPACE::GDCM_FILESEPARATOR 
714                                          + lastFilename + strExtent; 
715       else
716          fullWriteFilename = currentPatientWriteDir + GDCM_NAME_SPACE::GDCM_FILESEPARATOR 
717                                          + lastFilename + strExtent; 
718             
719       // Load the pixels in RAM.    
720       
721       fh = GDCM_NAME_SPACE::FileHelper::New(currentFile);     
722       uint8_t *imageData = fh->GetImageDataRaw(); // Don't convert (Gray Pixels + LUT) into (RGB pixels) ?!?
723       fh->SetWriteTypeToDcmExplVR();     
724       
725       if (rubout) {
726          // Put to Black the burnt-in number.
727          nX = currentFile->GetXSize();
728          nY = currentFile->GetYSize();
729          for(int y=nY-15; y<nY; y++)
730             for(int x=nX/3; x<nX/2+50; x++)
731               imageData[ y*nX*2 + x ] = 0;
732       }
733       
734       // We didn't make any computation on the pixels -> keep unchanged the following :
735       // 'Media Storage SOP Class UID' (0x0002,0x0002)
736       // 'SOP Class UID'               (0x0008,0x0016)
737       // 'Image Type'                  (0x0008,0x0008)
738       // 'Conversion Type'             (0x0008,0x0064)        
739       fh->SetContentType(GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE);
740       
741       if (!fh->Write(fullWriteFilename))
742       {
743          std::cout << "Fail to write :[" << fullWriteFilename << "]"
744                    << std::endl;
745       } 
746       fh->Delete();                
747    }
748    return 0;
749  }
750