#!/usr/bin/perl

my $infile=$ARGV[0];
my $outfile=$ARGV[1];

print "Converting SQL $infile\n";

if (!$infile) { print "Usage: $0 infile [outfile]\n"; exit 1 }

my $inhandle;
sysopen($inhandle,$infile,O_RDONLY | O_BINARY) || die "error opening file '$infile': $!";

my $size=-s $infile;

my $data;
sysread($inhandle,$data,$size) || die "Error reading from file '$infile', len=$size: $!";
close($infile); 

my @lines = split(/\n/,$data); my @out=();
foreach my $line (@lines) {
  $line =~ s/CREATE TABLE ([^\s]+) (/DROP TABLE $1 ; CREATE TABLE $1 (/gi;
  push @out,$line
}

$data=join("\n",@out);

if ($outfile) {
  my $outhandle;
  sysopen($outhandle,$outfile,O_CREAT | O_WRONLY | O_BINARY) || die "Error opening '$outfile' for writing: $!";
  syswrite($outhandle,$data) || die "Error writing to '$outfile': $!";
  close($outfile)
} else {
  print STDOUT $data
}

print "Converted SQL!\n"