#!/usr/local/bin/perl
#
#  perl script to convert "narrow" transactional data to "wide" format
#
#  input is in two columns:
#       transaction-id  product-id
#
#  output is a wide table:
#       transaction-id  count1  count2  count3  ...
#
#  where countN is quantity for product N (0 = didn't buy this product)
#
#  Typical Usage:
#       transact input-file > outfile           (convert to wide format)
#       dataschema outfile                      (create schema+datafiles)
#
#

#
# first pass: read everything into memory, creating 3 associative arrays:
#
#       %Pairs
#       %Products
#       %Transactions
#
# modificato lo split 27/04/2000
while (<>) {
        chop;                   # get rid on newline
        ($t, $p, $variable) = split/\t/; # split on multiple tab (Giorgio, 24 aprile 2000) 

        $Pairs{$t, $p}++;       # remember this pair
        $Products{$p} = 1;      # and this product-id
        $Transactions{$t} = 1;  # and this transaction-id
}


#
# sort the list of transactions and the list of products
# just to tidy things up
#
@Transactions = sort {$a <=> $b} keys %Transactions;    # numeric sort
@Products     = sort {$a cmp $b} keys %Products;        # dictionary sort

#
# print the titles (field names)
#
open (DV, ">mio.cname");
$i=0;
foreach $p (@Products) {
        print DV "$p \n";
	$i++;
}
#print DV "\n";
close (DV);
#
# -- loop over the transactions, print one customer visit per line
#
open (IN , ">mio.mat");
open (TRAN, ">mio.tran");

foreach $t (@Transactions) {
                             # print the transaction id
        print TRAN "$t\n";			     
        $column=1;
        foreach $p (@Products) {
	         
                $qty = $Pairs{$t, $p};
                $qty = 0 unless $qty;
                if ($qty != 0) {print IN  "$column $qty "; $total++};    # print quantity for this product
		$column++
        }
        print IN  "\n" ;
	$row ++;
	        #print IN  "$t \n";  	# end of record
}
close (IN);
close (TRAN);
open (FIRSTROW , ">mio.firstrow");
$column=$column-1;
print FIRSTROW "$row $column $total\n";
close (FIRSTROW);

#
# What follows the __END__ marker is just a sample input and output
# given for illustration purposes.  This is ignored by perl.
#
