#!/usr/bin/ruby
require "ftools"

if ARGV.length<4 then
  puts "Argumets: [Poisson input file] [p1] [p2] [step] [procs]"
  exit
end

# Read inn and interpret arguments
IN7file="Gap_to_hodo.in7"
InFName=ARGV[0]
FName_base=get_fname_base(InFName); 
p1=ARGV[1].to_f
p2=ARGV[2].to_f
pstep=ARGV[3].to_f
Procs= ARGV[4]==nil ? 2 : ARGV[4].to_i

if p1>p2 then p=p1; p1=p2; p2=p; 
else p=p1 end

# prepare run environment
outdir=FName_base.chop+"_PoleTiltScan_#{p1},#{pstep}_#{p2}"
prep_workspace(outdir)
File.copy("../"+InFName,".")


i=1; run_queue=[]
while p<=p2
  # prepare path organization strings
  puts (runpath="run_p#{p}")
  runbase=FName_base.chop+"_p#{p}"
  runpathbase=runpath+"/"+runbase
  Dir.mkdir(runpath)  # make run subdir
  
  # generate new input file from base and adjust current
  gen_amfile(p,InFName,runpathbase+".am") 
  system("echo #{p} `ruby ../AdjCur.rb "+runpathbase+".am 15000 25000 15000`>>p_vs_I.txt")

  # Generate interpolation file
  File.open(runpath+"/"+IN7file,"w") {|fid|   
    fid.printf("Line\r\n0 -30 0 100\r\n281\r\nEnd")}

  # generate batch file for running the Poisson sequence
  fid=File.open(runpathbase+".bat","w") {|fid|
    fid.write("@echo off\r\n start /low /w /min automesh "+runbase+\
              ".am\r\n start /low /w /min poisson\r\n sf7 "+\
              IN7file+" "+runbase+".T35")
    fid.chmod(0755)  }

  # run batch
  system("cmd /c \"cd "+runpath+" & "+runbase+".bat\""+\
         ((i % Procs)==0 ? "" : " &"))

  run_queue << runpath # collect run paths for result collection later

  p = ((p + pstep)*100).round.to_f/100;
  i+=1;
end

run_queue.each {|run| proc_results(run)} # result collection
system("unix2dos p_vs_I.txt")





# Functions

BEGIN{
  def gen_amfile(p,fname_in,fname_out)
    fout=File.open(fname_out,"w")
    File.open(fname_in) {|fin|
      while (line=fin.gets) != nil
        if (noteloc=line.index("VarTilt"))!=nil then
          sl=line.split(/[=,]/)
          if line[noteloc-1]=="+"[0] then newval=sl[1].to_f*(1+p)
          else newval=sl[1].to_f*(1-p) end
          fout.write(sl[0]+"=#{newval}, ")

        else
          fout.write(line)
        end
      end
    }
    fout.close
  end


  def proc_results(runpath)
    
    if (existResFile=File.exist?("Gap_to_hodo_field.txt")) then finold=File.open("Gap_to_hodo_field.txt") end
    fout=File.open("TmpResFile.txt","w")

    File.open(runpath+"/OUTSF7.TXT") {|fin| startrec=false
      while (str=fin.gets) != nil
        str2=str.split(' ')
        if startrec && str2.length==9 then
          if existResFile then
            str1=finold.gets.chop
          else
            str1=str2[1]
          end
          fout.write(str1+" "+str2[4]+"\r\n")
        else          
          startrec=(str2[1]=="(cm)" && str2[2]=="(G)")
        end
      end
    }
    fout.close; if existResFile then finold.close end
    File.move("TmpResFile.txt","Gap_to_hodo_field.txt")
  end

  
  def prep_workspace(outdir)
    Dir.mkdir(outdir)
    Dir.chdir(outdir)
    

  end
  
  def get_fname_base(fname)
    fname_split=fname.split('.'); 
    return fname.chomp(fname_split[fname_split.length-1])
  end
  
  
}  
