#!/usr/bin/ruby

require 'optparse'

argparams = ARGV.getopts("i:", "nowrite")

if argparams["i"].nil?
  STDERR.print "No file is given.\n"
  exit
end


def changeline( line, line_prev = nil )

  # comment
  if line[0].downcase == 'c'
    line[0] = '!'
  else

    # remove spaces and return at line end
    if line[-2] == ' '
      line = line.rstrip
    end

    # remove comment at line end
    i = line.rindex("!")
    if !i.nil?
      line = line[0..i-1]
    end

    # remove unexpected "?" in mtckd code
    i = line.rindex("?")
    if !i.nil?
      STDERR.print "Remove an unexpected '?' in MTCKD code.\n"
      line[i] = " "
    end

    # length of a line
#    if line.size > 80 # This results in a problem for the MTCKD.
    if line.size >= 80
      i = line.rindex(" ")
#      line.insert(i+1, '!')
      line = line[0..i]
    end

    # continuation
    if line.size >= 6
      if line[6-1] != ' '
        if line_prev.nil?
          puts 'Unexpected line continuation'
          exit
        else
          line[6-1] = ' '
          for l in 0..line_prev.size-1
            if line_prev[l][-1] != '&'
              line_prev[l] = line_prev[l].rstrip + "&"
            end
          end
        end
      end
    end

  end

  if line_prev.nil?
    return line
  else
    return line, line_prev
  end
end


def exclude_write_print( line_buf, line = nil )

  flag_write_print_continue = false
  for l in 0..line_buf.size-1
    if flag_write_print_continue
      line_buf[l].insert(0, "!")
      if line_buf[l][-1] == '&'
        flag_write_print_continue = true
      else
        flag_write_print_continue = false
      end
    end
    if line_buf[l].downcase.include?("write") || line_buf[l].downcase.include?("print")
      line_buf[l].insert(0, "!")
      if line_buf[l][-1] == '&'
        flag_write_print_continue = true
      end
    end
  end
  if flag_write_print_continue
    if !line.nil?
      line.insert(0, "!")
    end
  end

end


in_filename = argparams["i"]

in_file = open( in_filename, "r" )
line = in_file.gets
line = changeline( line )
line_prev = line
while line = in_file.gets
  #
  # check continuation
  flag_not_continue = true
  if line[0].downcase == 'c'
    flag_not_continue = false
  end
  if line.size >= 6
    if line[6-1] != ' '
      flag_not_continue = false
    end
  end
  #
  # change a current line and previous lines
  line, line_prev = changeline( line, line_prev )
  #
  # output
  if flag_not_continue
    if argparams["nowrite"]
      exclude_write_print( line_prev, line )
    end
    puts line_prev
    line_prev = [line]
    #print "# ", line_prev
  else
    line_prev = [line_prev, line]
    line_prev.flatten!
    #print "# ", line_prev, "\n"
  end
end
if argparams["nowrite"]
  exclude_write_print( line_prev )
end
puts line_prev
in_file.close
