#!/usr/bin/env ruby
#

=begin
-- autoimg -- ưŪ˲ե(*.jpg, *.png)õ <img src..> !


  ɤǤȤɤ󤫤ʬޤؤ󡣴ˡWeb
  ٱġ mkdiary.rbפĤƤ͸ĤƤ͡
  (http://www.gentei.org/~yuuji/diary/mkdiary/manual.html)

Ĥ

  * ᥤ⡼(mkdiary.rb -s) ƤӽФ
    Ĥޤꡢ~/.mkdiaryrc 

	bodyfilter=autoimg

    Ƚ񤤤Ƥ⤷body2html ȤȤ߹碌Ȥϡ

	bodyfilter=body2html|autoimg

    ߤ˥ѥ(|)ǷҤ

ᥤν

  źդ롣äΤϤ衣ǡʸϤĤΤ褦˽
  Τʤǡ<img src="hogehoge.jpg" ...> ߤ줿ʬ

	%IMG

  Ƚ񤭤ޤ礦źդ줿ե뤬ưŪõơimg˲
  ⤷ʣβźդ

	%IMG1
	%IMG2

  ߤIMGľ˲ܤ򼨤񤳡ֲܡ
  ʤΤϡźդΥե̾Ƿޤä㤦Τǡä֤Ʊ
  ˤʤ褦ʥե̾դƤʤȤ󤹡ޡ祸֤
  ͡

  ȡźդ٤imgѤȤ! äƤȤϡ

	%IMGS
  ޤ
	%IMG*

  ɤ⡢ǥ쥯ȥŸ줿եƤ
  imgѤ롣%IMGSξϡimg<br>Ƕڤä
  󤹤ΤGUIʥ֥饦ǸȤ˰˲ԤƲ¤֡
  %IMG* ξϳimg򤽤Τޤ¤٤Τǡ¤֡
  ۤ

¾

  ȡɤǤ⤨󤸤㤱ɡ֤㤢%IMGΤΤ񤭤
  Ϥɤ?פäƵ䤬Ф롣ꤸ͡ʤؤ
  ݤե륿ץǡפʤפȻפɡ⤷
  "%IMG" ΤΤ줿 "%%IMG" %ĽŤͤƤ٤
  Ǥ⤨͡

=end


$imgfiles = Dir.glob("*.{jpg,png,JPG,PNG}")

def charAt(handle, at)
  handle.seek(at, 0)
  return handle.read(1)[0]
end

def jpgsize(file)
  filesize=File.size(file)
  return nil if filesize < 2	# must have jpeg id (2bytes) at least
  open(file, "r"){|h|
    buf = h.read(2)
    comment=""
    return nil if buf[0] != 0xff || buf[1] != 0xd8
    seekpoint = 2
    catch (:exit) {
      while seekpoint < filesize-4
	if charAt(h, seekpoint) != 0xff then
	  throw :exit, 0
	elsif [192, 198, 194, 195, 197, 198, 199,
	    201, 202, 203, 205, 206, 207].index(charAt(h, 1+seekpoint)) then
	  # jpeg geometry area found!
	  h.seek(5+seekpoint, 0)
	  buf = h.read(4)
	  x = buf[2..3].unpack("n")[0]
	  y = buf[0..1].unpack("n")[0]
	  throw :exit, [x, y, comment]
	elsif 0xFE == charAt(h, 1+seekpoint) then
	  # JPEG comment area
	  h.seek(2+seekpoint, 0)
	  len = h.read(2).unpack("n")[0]
	  comment << h.read(len-2)+" "
	else
	  # Other marker
	  # Do nothing
	end
	seekpoint += 2
	h.seek(seekpoint, 0)
	buf = h.read(2)
	seekpoint += buf.unpack("n")[0]
      end
    }
  }
end

def pngsize(file)
  filesize=File.size(file)
  return if filesize < 0x18
  open(file, "r"){|h|
    buf = h.read(0x18)
    return nil if buf[0] != 0x89 || buf[1..3] != "PNG"
    x = buf[16..19].unpack("N")[0]
    y = buf[20..23].unpack("N")[0]
    return x, y
  }
end

def imgsrc(str)
  return "%" if str == "%%"	# %% escape
  if str == "%%" then
    return "%"
  elsif /IMG([S*])/ =~ str then
    sep = ($1 == "S") ? "<br>\n" : "\n"
    (0..$imgfiles.length-1).collect{|n|
      imgsrc("%IMG#{n}") + sep
    }.join('')
  elsif /IMG([0-9]?)/ =~ str then
    n = if $1 > "" then $1.to_i - 1 else 0 end
    alt = ''
    if /png$/i =~ $imgfiles[n] then
      xy = pngsize($imgfiles[n])
    elsif /jpg$/i =~ $imgfiles[n] then
      xy = jpgsize($imgfiles[n])
      alt = xy[2]
    end
    if xy then
      sprintf("<img src=\"%s\" alt=\"%s\" width=\"%d\" height=\"%d\">",
	      $imgfiles[n], (alt > "") ? alt : "photo", xy[0], xy[1])
    else
      sprintf("<img src=\"%s\" alt=\"photo\">", $imgfiles[n])
    end
  end
end



while line=gets
  line.gsub!(/%%|%IMG[0-9S*]?/){|s|imgsrc(s)}
  print line
end
