#!/usr/bin/env python

# Copyright 2009 Matteo Cesaroni, Lucilla Luzi
#
# This program is free software; ; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 3 of the License, or (at your
# option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
.

import sys
from rpy import *


def stop_err(msg):
    sys.stderr.write(msg)
    sys.exit()

def main():

    # Handle input params
    in_fname = sys.argv[1]
    out_fname = sys.argv[2] 
    #sys.stdout=open('log.txt','a')
    try:
        column = int( sys.argv[3] ) - 1
        column_x = int( sys.argv[4] ) - 1
        column_y = int( sys.argv[5] ) - 1
    except:
        stop_err( "..Column not specified, your query does not contain a column of numerical data." )


    title = sys.argv[6]

    skipped_lines = 0
    first_invalid_line = 0
    invalid_value = ''

    riga = []
    for tuo in range(1,1025):
       riga.append(int(0))
    #print riga
    
    matrice = []
    for mio in range(1,769):
        #print mio
        matrice.append(riga)
    
    #print matrix
    matrix1 = array(matrice)
    #print matrix1
    for i, line in enumerate( file( in_fname ) ):
        valid = True
        line = line.rstrip('\r\n')
        # Skip comments
        if line and not line.startswith( '#' ): 
            # Extract values and convert to floats
            row = []
            val = 0
            val_x = 0
            val_y = 0
            try:
                fields = line.split( "\t" )
                val = fields[column]
                val_x = (int(fields[column_x])-1)
                val_y = (int(fields[column_y])-1)
                matrix1[val_x][val_y]=float(val)
                
                
            except:
                valid = False
                skipped_lines += 1
                if not first_invalid_line:
                    first_invalid_line = i+1
            else:
                try:
                    row.append( float( val ) )
                except ValueError:
                    valid = False
                    skipped_lines += 1
                    if not first_invalid_line:
                        first_invalid_line = i+1
                        invalid_value = fields[column]
        else:
            valid = False
            skipped_lines += 1
            if not first_invalid_line:
                first_invalid_line = i+1
                
    output_prima=sys.stdout
    fsock=open('log.txt','w')
    sys.stdout=fsock
    
    
    for i in range(768):
      for j in range(1024):
        if j<1022:
          print "%s\t" %matrix1[i][j],
        if j==1023:
          print "%s" %matrix1[i][j]
    sys.stdout=output_prima
    fsock.close()      
    
    set_default_mode(NO_CONVERSION)
    if skipped_lines < i:
        #print "..on columnn %s" %sys.argv[3]
        a=r.read_table("log.txt")
        b=r.as_matrix(a)
        #r.print_(b)
        #b=r.cbind(a[1],a[1])
        r.pdf( out_fname, 8, 8 )
        r.image(z=r.log2(b),col=r.terrain_colors(100000),main=title, xlab="X", ylab="Y")
        r.dev_off()
        
    else:
       print "..all values in column %s are non-numeric." %sys.argv[3]

    if skipped_lines > 0:
        print "..skipped %d invalid lines starting with line #%d.  Value '%s' is not numeric." % ( skipped_lines, first_invalid_line, invalid_value )

    r.quit( save="no" )
    
if __name__ == "__main__":
   main()

