#!/usr/bin/perl -w -s

#Gera código SQL (postgresql) do dicionário aberto.


$/ = "\n\n";

use utf8;

use warnings;
use strict;
our ($scratch);

use POSIX qw(locale_h);
setlocale(LC_CTYPE, "pt_PT.UTF8");
use locale;

our $o="/* Fazer \"createdb dicAberto  -E UTF8\" na consola */\n";
$o.="/* Depois: \"psql dicAberto -f dicAbertoPG.sql\"*/ \n";

$o.="BEGIN;\n";

$o.="CREATE TABLE dict (id serial primary key, word varchar(60), def text);\n";

sub ins{
    my ($w,$t)=@_;
    $t=~s!\'!\\\'!g;
    $o.="INSERT INTO dict(word,def) VALUES ('$w','$t');\n"
}

my $term;
my $progress = 0;
print STDERR "Processing";
while(<>) {
  chomp;

  my @lines = split /\n/;

  $term = lc(shift @lines);
  $term =~ s/,$//g;

  $term =~ s!\*!!g;
  $term =~ s!\+!!g;
  $term =~ s!\}!!g;
  $term =~ s!\{!!g;

  $term =~ s!^\s*!!g;
  $term =~ s!\s*$!!g;
  $term=~s!\'!\\\'!g;

  my $word = $term;
  $word =~ s!,.*$!!;
  $word =~ s!\^.*$!!;

  &ins($word, join(" ", @lines));

  $progress++;
  print STDERR "." unless $progress % 500;

}

print STDERR "\nLast insertion: '$term'\n";

$o.="CREATE INDEX wordidx ON dict(word);\n";
$o.="COMMIT\n";
print "$o\n";
