#!/usr/local/bin/ruby
# -*- coding: utf-8 -*-
require 'sqlite3'
require 'kconv'
dbfile = "vote.sq3"
max=(ENV["MKG_MAX"] || "100").to_i
team = Hash.new
votetbl = "vote.tbl"
IO.foreach(votetbl) do |x|
  x = x.toeuc
  sname, gname = x.scan(/([-0-9a-z]+)\s+(.*)/i)[0]
  next unless sname && gname
  team[sname] = gname
end
if test(?e, "openat")
  date = IO.readlines("openat")[0].chomp
  if Time.now.strftime("%F %T") < date
    printf("
%s に開票します.
", date)
    exit 0
  end
end
mydir=File.expand_path(File.dirname($0))
table=(ARGV[0]||File.basename(mydir))
point = Hash.new(0)
if test(?s, dbfile)
  db = SQLite3::Database.new("vote.sq3")
  db.transaction do
    db.execute("select team,sum(point) from #{table} group by team;") do |row|
      point[row[0]] = row[1].to_i
    end
    #db.results_as_hash = true
    #p db.execute("select team,sum(point) from #{table} group by team;")
  end
end
puts ''
for t in team.keys.sort{|x, y| point[y] <=> point[x]}
  print " \n  | "
  printf("%s (%3d) | \n", team[t], t, point[t])
  pt = point[t]
  print "  \n   "
  #printf ' ', pt, pt
  printf '', max, pt
  puts " | 
\n"
end
puts '
'