#!/usr/local/bin/python
#

"read a file of tab-separated fields and create a .ace file"

# 
# Version 11/ 5/05
#
# Synopsis: tsv2ace.py tsvfile acefile


import sys
import os
import string
import re

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class Parameters :
      "Wrapper class for command line parameters"

      def __init__(self) :
          self.IFN = ""
	  self.OFN = ""
	  

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def READARGS(P) :
    "Read command line arguments into a Parameter object"
    NUMARGS = len(sys.argv)
    if NUMARGS >= 1 :
       P.IFN = sys.argv[1]

    I = 2
    while (I < NUMARGS)  :
             P.OFN = sys.argv[I]
             I = NUMARGS	             	
    return

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Data in tabular form, from tsvfile."

class TABLE :
    def __init__(self) :
        self.heading = [] # non-blank column headings
	self.columns = [] # list of column numbers with non-blank headings
        self.row = [] # data from each subsequent row

    """The first row in the table (ie., the first line in the file)
    is read as column headings. All subsequent rows are read as data. 
    If a column has a blank heading, that column will be skipped."""   
    def readtsvfile(self,IFN) :
        INFILE = open(IFN,'r')
	LINE = INFILE.readline()
	
	# Read column headings from first line.
	TOKENS = string.split(string.strip(LINE),"\t")
	for HEADING in TOKENS :
	    if HEADING != "" :
	       T.heading.append(HEADING)
	       T.columns.append(TOKENS.index(HEADING))
	   
	# Read data from the remaining rows of the table
	LINE = INFILE.readline()
	while not (LINE == "") :
	   TOKENS = string.split(string.strip(LINE),"\t")
	   R = []	   
	   for TOKEN in TOKENS :
	          R.append(TOKEN)		
	   T.row.append(R) 
	   LINE = INFILE.readline()
      	    
        INFILE.close()
        return             
        
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#class AceClass :
      #"Class definition for an ACEDB class"
     # 
      #class Field :
            #def __init__(self) :
	    #self.fieldname = ""
	    #self.value = []
#
      #def __init__(self) :
          #self.classname = ""
	  #self.items = []
	 # 
      #def readmodels(self,MFN) :
     # 
        #def findmodel(MFN) :
            #LINE = MFILE.readline()
	    #while not (re.match('^\?') and (not LINE == "")
               #LINE = MFILE.readline()	 
	    #return LINE
	   # 
        #MFILE = open(MFN,'r')
        #LINE = findmodel(MFN)
	#while not (LINE == "") :
	   #TOKENS = string.split(LINE,' ')
	   #self.classname = TOKENS[0][1:]
	  # 
#	
	#MFILE.close()	
	#return          


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class Program :

      def __init__(self) :
          self.name = ""
	  self.pkg = ""
	  self.category = []
	  self.doc = []
	  self.platform = ["solaris-sparc","solaris-amd64","linux-intel"]
	  self.interface = ""

      def writeprog(self,OUTFILE) :
          OUTFILE.write("\n")
	  OUTFILE.write(" // Class Program" + "\n")
          OUTFILE.write("\n")
	  OUTFILE.write('Program :\t "' + self.name + '"\n')
	  if self.pkg != "" :
	     OUTFILE.write('Package \t "' + self.pkg + '"\n')
          for CAT in self.category :
	      if CAT != "" :
	         OUTFILE.write('Category \t "' + CAT + '"\n')	      
          for DOCUMENT in self.doc :
	      if DOCUMENT != "" :
	         DOCUMENT = DOCUMENT.replace('/','\/')
	         OUTFILE.write('Documentation \t "' + DOCUMENT + '"\n')
	  if self.interface != "" :
	     if self.interface == "both" :
	        OUTFILE.write('Interface \t "command" \"' + self.name + ' [options]' + '"\n')
	        OUTFILE.write('Interface \t "interactive" \"' + self.name + '"\n')
	     elif self.interface == "command" :
	        OUTFILE.write('Interface \t "command" \"' + self.name + ' [options]' + '"\n')
	     elif self.interface == "interactive" :
	        OUTFILE.write('Interface \t "interactive" \"' + self.name + '"\n')	     
	     elif self.interface == "gui" :
	        OUTFILE.write('Interface \t "gui" \"' + self.name + ' [filename]' + '"\n')
	     else :
	        OUTFILE.write('Interface \t "' + self.interface + '"\n')
		
          # WARNING: HACK! For the purposes of populating the database, we 
	  # tell ACeDB that all programs are on all platforms, and then manually 
	  # edit out that information in ACeDB. This is cheesy, but it's much
	  # quicker than putting in all that platform info. by hand.		
	  OUTFILE.write('Platform \t "' + 'solaris-sparc' + '"\n')	      	      
          OUTFILE.write('Platform \t "' + 'solaris-amd64' + '"\n')
	  OUTFILE.write('Platform \t "' + 'linux-intel' + '"\n')
	      	    
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class Package :

      def __init__(self) :
          self.pkgname = ""
	  self.program = []
	  self.category = []
	  self.doc = []	  
	  self.platform = ["solaris-sparc","solaris-sparc","linux-intel"]
	  	  
   
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class Category :

      def __init__(self) :
          self.catname = ""
	  self.program = []
	  self.pkg = []
 

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class File :

      def __init__(self) :
          self.name = ""
	  self.command = '\"$ACE_FILE_LAUNCHER\" '
	  self.path = "" 

      def writefile(self,OUTFILE) :
          OUTFILE.write("\n")
	  OUTFILE.write(" // Class File" + "\n")
          OUTFILE.write("\n")
	  self.name = self.name.replace('/','\/')
	  self.path = self.path.replace('/','\/')
	  OUTFILE.write('File :\t "' + self.name + '"\n')   
	  OUTFILE.write('Pick_me_to_call \t ' + self.command + '\"' + self.path +'"\n')	   
	  	      	      
#======================== MAIN PROCEDURE ==========================
P = Parameters ()

READARGS(P)
OUTFILE = open(P.OFN,'w')

# Read in a tab-separated file
T = TABLE ()
T.readtsvfile(P.IFN)
print T.heading
print T.columns

# ------------------ Create program objects -------------------------
prognames = [] # names of programs that have already been created.
programs = [] # programs that have already been created.

COL = T.heading.index("Program")
for R in T.row :
    Name = R[COL]
    if Name != "" :
       if (Name in prognames) :
	  pass
       else :
	  PROG = Program()
	  PROG.name = Name
	  PROG.pkg = R[T.heading.index("Package")]
	  PROG.category.append(R[T.heading.index("Category")])
	  FILEINDEX = T.heading.index("File")
	  if len(R) > FILEINDEX : # not all entries hava a File field
             PROG.doc.append(R[FILEINDEX])
	  INTERFACEINDEX = T.heading.index("Interface")
	  if len(R) > INTERFACEINDEX : # not all entries have an interface field
             PROG.interface = R[INTERFACEINDEX]
	  programs.append(PROG)
	  print Name

# ------------------ Create file objects -------------------------
filenames = [] # names of files that have already been created.
files = [] # files that have already been created.

COL = T.heading.index("File")
for R in T.row :
    if len(R) > COL :  
       FPath = R[COL]
       if FPath != "" :
	  if (FPath in filenames) :
	     pass
	  else :
	     F = File()
	     F.path = FPath
	     F.name = FPath	  
	     files.append(F)
	     print FPath 
	     
# ------------------- ACeDB flatfile --------------------------

for PROG in programs :
    PROG.writeprog(OUTFILE)

for F in files :
    F.writefile(OUTFILE)
    
OUTFILE.close()    
