#!/usr/bin/ruby

# http://taro-tnk.hatenablog.com/entry/2012/12/17/001552
def float_string?(str)
  Float(str)
  true
rescue ArgumentError
  false
end

indir = "data3"
infile = ["Warren1986_p2663-1.txt", "Warren1986_p2663-2.txt", "Warren1986_p2663-3.txt", "Warren1986_p2664-1.txt", "Warren1986_p2664-2.txt", "Warren1986_p2664-3.txt", "Warren1986_p2665-1.txt", "Warren1986_p2665-2.txt", "Warren1986_p2665-3.txt", "Warren1986_p2666-1.txt", "Warren1986_p2666-2.txt", "Warren1986_p2666-3.txt", "Warren1986_p2667-1.txt", "Warren1986_p2667-2.txt", "Warren1986_p2667-3.txt"]
outfile = "data4/Warren1986.txt"
print "Output: ", outfile, "\n"

# Preparation
columns = [[""]]
columns << [""]
columns << [""]
#  p columns

for ifile in 0..infile.length-1
  fn = indir+"/"+infile[ifile]
  File.open(fn, mode = "rt"){|f|
    for n in 0..3-1
      for l in 0..189/3-1
        line = f.gets
        lineorg = line
        # delete blank
        line = line.gsub(/[" "*]/, "").gsub(/[Oo]/, "0").gsub("+C", "+0").gsub(/[iIl]/, "1").gsub("5+", "E+").gsub("5-", "E-").gsub(",", ".")
        if !float_string?(line) then
          print "Chage value: ", line.chomp, " (", lineorg.chomp, ") in ", infile[ifile], " at ", 189/3*n+l+1, "th line\n"
          #            line = gets
        end
        #      print line
        columns[n] << line
        if n == 0 then
          if !(ifile == 0 && l == 0) then
            if columns[0][-2].to_f > columns[0][-1].to_f then
              print "Order is inappropriate: ", line.chomp, " (", lineorg.chomp, ") in ", infile[ifile], " at ", 189/3*n+l+1, "th line\n"
            end
          end
        end
      end
    end
  }
end

#p columns
#p columns[0].length
File.open(outfile, "w") do |f|
  for l in 0+1..columns[0].length-1
    f.puts(columns[0][l].chomp+" "+columns[1][l].chomp+" "+columns[2][l].chomp+"\n")
  end
end
