#!/bin/perl -w

# 1) You need to modify the filename

unless (open FILE, "yourfilename.bib") {
    die "Unable to open file.  The filename is hardcoded in this script.";
}

# 2) as well as the field list that you want to export.

@allfields = ("type","key", "title", "author",  "publisher", "year", "address", "isbn");


@lines = <FILE>;
close FILE;
@modified = ();


%record = ();

while (@lines) {
    $line = shift @lines;
    
    #Chop newline character
    chomp($line);
    
    $line =~ s/,$/\#\#/;
    
    if ( $line =~ /^@/ ) {
	unshift (@modified, $longline);
	$longline = $line;
    } else {
	$longline .= $line;
    }
    
}

while (@modified) {
    $line = shift @modified;
    
    if ($line =~ /^@(.*?){(.*)}/) {
	@fields = split "\#\#", $2;
	$fields[0] = "key = $fields[0]";
	unshift(@fields, "type = $1");

	foreach $raw (@fields) {
	    ($title, $value) = split "=", $raw;
	    $value =~ s/^\s*"(.*)"\s*$/$1/;
	    $title =~ s/^\s*(\S.*?)\s*$/$1/;

	    $record{$title} = $value;
	}

	unshift (@database, { %record } ); 
    }
    
}


foreach $ref (@database) {
    @entry = ();

    foreach $title (@allfields) {
	if ( ! $$ref{$title} ) {
	    $$ref{$title} = "";
	}

	push (@entry,  $$ref{$title} );
    }

    print join "\t", @entry;
    print "\n";
}




