#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Giovanni Lombardo 2009 (Commented part was  mostly taken from http://www.unix.com/newreply.php?do=newreply&p=302239976; current part reconstructed from Python web pages

# 29 April 2009: give two inputs: name of excel file (no extension) and keyword of worksheet (it is going to extract all worksheets containing that keyword)

import pyExcelerator,os
from pyExcelerator import *
import sys
import xlrd
import xlwt
import string
import re
import getopt
import math
#def extract_sheets (args,sheetkey):

#sheetkey= raw_input("Enter the key for the worksheet to be extraced -->")

tmp=sys.argv[1:]
print tmp
z=1;
for numarg in tmp:
  #print 'loop'
  if z==1:
    args=[numarg]
  elif z==2:
    sheetkey=numarg
  z=z+1
#print 'counter',z
#print 'sheetkey', sheetkey
#print 'args', args
#input_list=getopt.getopt(sys.argv[1:],["."])
#print input_list[1][0]
#sheetkey=input_list[1][1]
#args=input_list[1][0]
#print "doing ",args

#Alternatively get the strings following the call
#me, args = sys.argv[0], sys.argv[1:]

#test=sys.argv[1:].split()



#x=[]
#y=[]
#IN=True
#print 'input name(s) of worksheets [blank if all] '

#xt=raw_input()
#print ' list of worksheets: ==>> '+xt
#dirname = "extracted"
#if not os.path.isdir("./" + dirname + "/"):
  #os.mkdir("./" + dirname + "/")


#for arg in args:
    #book =pyExcelerator.parse_xls(arg+".xls")
    #curpath = os.path.dirname(__file__)
    #for items in book:
	#sheetname=items[0]
	#contents=items[1]
	#workbook = pyExcelerator.Workbook()
	#worksheet = workbook.add_sheet("Sheet 1")    
	#for key,value in contents.iteritems():
	    ##print "key ",key, " value: ",value
	    #worksheet.write(key[0],key[1], value)
	    #workbook.save(os.path.join(curpath, "extracted/"+arg+sheetname+".xls"))
number_total=1;
for arg in args:
    print arg
    book =xlrd.open_workbook(arg+".xls")
    
    print "number of total worksheets is" , book.nsheets
    #print "Worksheet name(s):", book.sheet_names()
    nsh = book.nsheets
    for sheet in  book.sheet_names():
      if re.search(sheetkey, sheet) :# Match:
	number_total=number_total+1;
	merged_book = xlwt.Workbook() 
	out_file="extracted/"+arg+sheet+".xls"
	ws = merged_book.add_sheet(sheet)
	sheet2 = book.sheet_by_name(sheet)
	for rx in range(sheet2.nrows):
	  for cx in range(sheet2.ncols):
	    ws.write(rx, cx, sheet2.cell_value(rx, cx)) 
	merged_book.save(out_file)

    print "---> Extracted xls file written to %s : " % "extracted/"+arg+"....xls" 
print "---> Extracted %i sheets: " % number_total
