#!/usr/bin/perl

open(IN,$ARGV[0]) or die "Could not open file $ARGV[0] for input.\n";
#open(OUT,">",$ARGV[1]) or die "Could not open file $ARGV[1] for output.\n";

@inputfile = <IN>;
close IN;
@paperhash = (); # A list of hashes representing paper qualities
$thishash = {};
foreach $p (@inputfile) { # read lines from the input file
  if ($p eq "\n") { # A blank line indicates that we are talking about a new paper now!
    push(@paperhash,$thishash);
    $thishash = {}; # Create a key/value hash representing this article
  }
  foreach $kv (split(/\n/gs,$p)) {
    chomp $kv;
    ($key,@value) = split(/=/,$kv); # The part before the = is the key; the part after is the value.
    $val = join("=",@value); # But values can contain the '=' symbol character
#    print "line is $kv, key $key, val $val, scalar is ".scalar(@paperhash)."\n";
    if ($key eq "author") {
      push(@{$thishash->{$key}},$val); # Authors are always in an ORDERED list
    }
    else {
      $thishash->{$key} = $val; # Other fields are not repeated, so the last one listed is the one used
    }
  }
}

foreach $p ( sort { $a->{"startpage"} <=> $b->{"startpage"} } @paperhash ) { # If the .dat was not in page order, make sure the output is
  next unless $p->{"title"}; # Skip this item if the paper has no title (probably an extra newline in the data file)
  @outfile = split('/',$p->{html});
  $outfile = @outfile[1]; # CHANGED BY JB AFTER STARTED USING YEAR AT BEGINNING; WAS 0
#  open(OUT,">","jdm/journl/".$outfile.".rdf");
  open(OUT,">",$outfile.".rdf"); # then move to jdm/journl after making notification
  print OUT "Template-Type: ReDIF-Article 1.0\n";
  foreach $author ( @{$p->{"author"}} ) {
    print OUT "Author-Name: $author\n";
  }
  print OUT "Title: ".$p->{"title"}."\n";
#  print OUT "Classification-JEL: ".$p->{"jel"}."\n";
#  print OUT "Keywords: ".lc($p->{"keywords"})."\n";
  print OUT "Journal: Judgment and Decision Making\n";
  print OUT "Pages: ".$p->{"startpage"}."-".$p->{"endpage"}."\n";
  print OUT "Volume: ".$p->{"volume"}."\n";
  print OUT "Issue: ".$p->{"issue"}."\n";
  print OUT "Year: ".$p->{"year"}."\n";
  print OUT "Month: ".$p->{"month"}."\n";
  print OUT "File-URL: http://journal.sjdm.org/".$p->{"pdf"}."\n";
  print OUT "File-Format: Application/pdf\n";
  print OUT "File-URL: http://journal.sjdm.org/".$p->{"html"}."\n";
  print OUT "File-Format: text/html\n";
  print OUT "Handle: RePEc:jdm:journl:v:".$p->{"volume"}.":y:".$p->{"year"}.":i:".$p->{"issue"}.":p:".$p->{"startpage"}."-".$p->{"endpage"}."\n";
  # This is the handle suggested by the RePEc page.
#  print OUT "\n";
}
