#!/usr/bin/perl -w
use strict;

my @element=qw(
title
author
email
booktitle
journal
volume
number
publisher
address
editor
pages
year
month
isbn
url
misc
);

# if (/^@\w+{\s*(\w+),(.*?)}/sg)

while(<>)
{
  if (/^\@\w+\s*{\s*([\w\-]+),/)
  {
    my $tag=$1;
    # warn $tag;
    my $content="";
    while(<>)
    {
      last if /^}/;
      $content .= $_;
    }
    # print "$tag\n";
    my @content=split(",\n",$content);
    my %content;
    for my $item (@content)
    {
      $item =~ /(\w+)\s*=\s*({|")(.*)("|})/;
      my $var=$1;
      my $val=$3;
      warn "bad format in $tag: $item\n" unless $var && $val;
      warn "unknown element $var in $tag\n" unless grep /^$var$/, @element;
      $content{$var}=$val;
    }

    my $out="\n<reference name='$tag'>\n\t";

    for my $e (@element)
    {
      next unless $content{$e};
      next if $e eq "address";
      delete $content{'url'} if $content{'year'};
      delete $content{'url'} if $content{'isbn'};
      my $val=$content{$e};
      my $segment="$val, ";
      for ($e)
      {
	/^title$/ && ($segment="<i>$val</i>, ");
	/^pages$/ && ($segment="pp. $val, ");
	/^isbn$/ && ($segment="ISBN $val, ");
	/^volume$/ && ($segment="vol $val, ");
	/^number$/ && ($segment="num $val, ");
	/^url$/ && ($segment="<a href='http://$val'>http://$val</a>, ");
      }
      $out.=$segment;
    }

    $out =~ s/, $//;
    $out .= "\n</reference>\n";
    print $out;
  }
  else
  {
    print;
  }
}


__DATA__

@inproceedings{ nordin95evolving,
  author = "Peter Nordin and Wolfgang Banzhaf",
  title = "Evolving Turing-Complete Programs for a Register Machine with Self-modifying Code",
  booktitle = "Genetic Algorithms: Proceedings of the Sixth International Conference (ICGA95)",
  month = "15-19",
  publisher = "Morgan Kaufmann",
  address = "Pittsburgh, PA, USA",
  editor = "L. Eshelman",
  isbn = "1-55860-370-0",
  pages = "318--325",
  year = "1995",
  url = "citeseer.nj.nec.com/nordin95evolving.html"
}

