#!/usr/koeki/bin/ruby
#coding: euc-jp

require 'cgi'

cgi = CGI.new(:accept_charset => "EUC-JP")
print("Content-type: text/html; charset=EUC-JP\n\n")

bus = Hash.new

direc = cgi["direc"]
dep = cgi["dep"]
arr = cgi["arr"]
hour = cgi["hour"]
min = cgi["min"]
which = cgi["which"]

if direc == "e"
  open("/home/irhome/c110/c110188/Ruby/zikoku1.txt","r:euc-jp") do |zikoku|
    while line = zikoku.gets 
      if /(\S*),(\S*),(\S*),(\S*),(\S*),(\S*),(\S*),(\S*),(\S*),(\S*)/ =~ line
        bus[$10.to_s] = [$1.to_i,$2.to_i,$3.to_i,$4.to_i,$5.to_i,
                         $6.to_i,$7.to_i,$8.to_i,$9.to_i]
      end      
    end
  end
  
elsif direc == "k"
  open("/home/irhome/c110/c110188/Ruby/zikoku2.txt","r:euc-jp") do |zikoku|
    while line = zikoku.gets
      if /(\S*),(\S*),(\S*),(\S*),(\S*),(\S*),(\S*),(\S*),(\S*),(\S*)/ =~ line
        bus[$10.to_s] = [$1.to_i,$2.to_i,$3.to_i,$4.to_i,$5.to_i,
                         $6.to_i,$7.to_i,$8.to_i,$9.to_i]
      end      
    end
  end
end

time = hour + min

# p time

print("<html>\n")
print("<head>\n")
print("<title>結果</title>\n")
print("</head>\n")
print("<body>\n")
print("<link rel=\"stylesheet\" href=\"ruru.css\" type=\"text/css\">\n")
print("<h1>検索結果</h1>\n")

a = 0
if which == "t"
    while true
      if time.to_i < bus[arr][0]
        print("<h2>乗車</h2>")
        printf("<p> %s %d\n</p>\n",dep,bus[dep][8])
        printf("<p>下車 %s %d\n</p>\n",arr,bus[arr][8])
        break
      elsif a >= 8 || time.to_i > bus[arr][a] && time.to_i < bus[arr][a+1]
        print("<h2>乗車</h2>")
        printf("<p>%s %d\n</p>\n",dep,bus[dep][a])
        print("<h2>下車</h2>")
        printf("<p>%s %d\n</p>\n",arr,bus[arr][a])
        break
      else 
        a += 1 
      end
    end
elsif which == "s"
  while true
    if time.to_i < bus[dep][0] || time.to_i > bus[dep][8]
      printf("<p>乗車 %s %d\n</p>\n",dep,bus[dep][0])
      printf("<p>下車 %s %d\n</p>\n",arr,bus[arr][0])
      break
    elsif time.to_i > bus[dep][a] && time.to_i < bus[dep][a+1]
      printf("<p>乗車 %s %d\n</p>\n",dep,bus[dep][a+1])
      printf("<p>下車 %s %d\n</p>\n",arr,bus[arr][a+1])
      break
    else 
      a += 1 
    end
  end
end

print("</body>\n")
print("</html>\n")
