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