#!/usr/bin/perl

use Cwd;

# 10 MeV wide bins
$nBins = 100;

$fitName = "d2pi_fit";

# this directory can be adjusted if you want to do the fit elsewhere
# but it needs to be an explicit path
$workingDir = getcwd();

# config file
$cfgTempl = "$workingDir/fit.cfg";

# these files must exist in the working directory.  If you don't know how
# to generate them or don't have them, see the documentation in gen_3pi
# the Simulation area of the repository
$dataFile = "$workingDir/data.root";
$accMCFile = "$workingDir/acc.root";
$genMCFile = "$workingDir/gen.root";

### things below here probably don't need to be modified

# this is where the goodies for the fit will end up
$fitDir = "$workingDir/$fitName/";
mkdir $fitDir unless -d $fitDir;

chdir $fitDir;

# extract the file name
@dataParts = split /\//, $dataFile;
$dataTag = pop @dataParts;
$dataTag =~ s/\.root//;

@accMCParts = split /\//, $accMCFile;
$accMCTag = pop @accMCParts;
$accMCTag =~ s/\.root//;

@genMCParts = split /\//, $genMCFile;
$genMCTag = pop @genMCParts;
$genMCTag =~ s/\.root//;

# make directories to perform the fits in
for( $i = 0; $i < $nBins; ++$i ){

  mkdir "bin_$i" unless -d "bin_$i";

  chdir "bin_$i";

  open( CFGOUT, ">bin_$i.cfg" );
  open( CFGIN, $cfgTempl );

  while( <CFGIN> ){

    s/DATAFILE/$dataTag\_$i.root/;
    s/ACCMCFILE/$accMCTag\_$i.root/;
    s/GENMCFILE/$genMCTag\_$i.root/;
    s/NIFILE/bin_$i.ni/;
    s/FITNAME/bin_$i/;

    print CFGOUT $_;
  }

  close CFGOUT;
  close CFGIN;
  
  system( "touch param_init.cfg" );

  chdir $fitDir;
}

