#!/usr/bin/perl
# quick hack:
# export your PTSB stuff to XLS, then save as csv, then run this over
# it, and you should be able to feed it to YNAB.
use warnings;
use strict;
use Text::CSV_XS;

my ( $input, $output ) = @ARGV;
die "No input file specified" unless $input;
die "No output file specified" unless $output;

my $csv = new Text::CSV_XS( { binary => 1 });

my @rows;
open my $fh, "<:encoding(utf8)", $input or die "fail: $!";
while ( my $row = $csv->getline( $fh )) {
    next unless $row->[0] =~ /^\d+/;
    push @rows, $row;
}
$csv->eof or $csv->error_diag();
close($fh);

$csv->eol("\r\n");
open $fh, ">:encoding(utf8)", $output or die "fail 2: $!";
$csv->print( $fh, [ "Date", "Payee", "Category", "Memo", "Outflow", "Inflow" ]);
for my $row ( @rows ) {
    # rearrange fields
    my $newrow = [
                  $row->[0], # date
                  $row->[1], # Payee
                  "",        # Category
                  $row->[1], # Memo
                  $row->[3] < 0 ? abs($row->[3]) : 0,  # Out
                  $row->[3] > 0 ? abs($row->[3]) : 0,  # In
                 ];

    $csv->print( $fh, $newrow );
}
close( $fh ) or die "fail 3: $!";
