#!/opt/local/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
import urllib2
import urllib
import optparse
import os
import platform
import sys
import json
import csv
import codecs
import HTMLParser
from UnicodeCSV.UnicodeCSV import UTF8Recoder
from UnicodeCSV.UnicodeCSV import UnicodeReader
from UnicodeCSV.UnicodeCSV import UnicodeWriter
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers 
import re
from htmlentitydefs import name2codepoint
import WebBrowser.webbrowser as webbrowser
import shutil
import urlparse


def module_path():
	if hasattr(sys, "frozen"):
		return os.path.dirname(os.path.abspath(unicode(sys.executable, sys.getfilesystemencoding( ))))
	return os.path.dirname(os.path.abspath(unicode(__file__, sys.getfilesystemencoding( ))))

def download(url, fileName=None):
	def getDirectory():
		dirname = os.path.join(os.path.abspath(os.path.expanduser("~")),"Downloads")
		if os.path.isdir(dirname):
			return dirname
		else:
			return os.path.join(os.path.abspath(os.path.expanduser("~")),"Desktop")
	def getFileName(url,openUrl):
		if 'Content-Disposition' in openUrl.info():
			cd = dict(map(lambda x: x.strip().split('=') if '=' in x else (x.strip(),''),openUrl.info()['Content-Disposition'].split(';')))
			if 'filename' in cd:
				filename = cd['filename'].strip("\"'")
				if filename: return filename
		return os.path.basename(urlparse.urlsplit(openUrl.url)[2])
	directoryfound = False
	directory = getDirectory()
	if os.path.isdir(directory):
		directoryfound = True
	else:
		directoryfound = False
		return directoryfound
	try:
		r = urllib2.urlopen(urllib2.Request(url))
		fileName = fileName or getFileName(url,r)
		absfilename = os.path.join(directory,fileName)
		with open(absfilename, 'wb') as f:
			shutil.copyfileobj(r,f)
	finally:
		r.close()
		return True
	return False

def checkVersion():
	f = urllib.urlopen("https://www.crmondemand.biz/CL/version.txt")
	s = f.read().strip()
	eq = s.rfind('=')
	onlineversion = ""
	if eq>-1 and eq != False:
		onlineversion = s[eq:].strip()
	f.close()
	scriptdir = module_path()
	versionfile = os.path.join(scriptdir, 'version.txt')
	try:		
		curversion = open(versionfile, 'r').read().strip()
	except IOError as e:
		print "Version file has been removed, are you using MacPorts to keep HeapCL up-to-date?"
		return False
		curversion = ""
	eq = curversion.rfind('=')
	if eq>-1 and eq != False:
		curversion = curversion[eq:].strip()
	if curversion == onlineversion and len(curversion)>0:
		print "Version up to date"
	else:
		if platform.system() == 'Windows':
			print "Version out of date, opening web browser"
			webbrowser.open("http://heap.wbpsystems.com/cl.php#Setup")
		else:
			print "Version out of date, attempting to download update to Downloads folder"
			downloadoutcome = download("https://www.crmondemand.biz/CL/heapCL.tar.gz")
			if downloadoutcome != True:
				print "Couldn't download file, opening web browser"
				webbrowser.open("http://heap.wbpsystems.com/cl.php#Setup")
			else:
				print "File downloaded"

def myNewLine():
	if platform.system() == 'Windows':
		return "\r\n"
	else:
		return "\n"


def htmlentitydecode(s):
    return re.sub('&(%s);' % '|'.join(name2codepoint), 
            lambda m: unichr(name2codepoint[m.group(1)]), s)
def saveWebHook(webhook):
	string = ''
	webhook = webhook.strip()
	o = urlparse.urlparse(webhook);
	
	if (o.scheme.lower() == 'http' and webhook.find(' ')==-1) or (o.scheme.lower() == 'https' and webhook.find(' ')==-1):
		string = 'Valid WebHook: ' + webhook
	else:
		print 'Instructed to save invalid WebHook'
		sys.exit()
	
	if platform.system() == 'Windows':
		savefile = 'heapcrm_cl.ini'
	else:
		savefile = ".heapcrm_cl"

	configfile = os.path.join(os.path.expanduser("~"), savefile)
	f = open(configfile, 'w')
	f.write(webhook)
	f.close()
	return string
	
def getWebHook():
	if platform.system() == 'Windows':
		savefile = 'heapcrm_cl.ini'
	else:
		savefile = ".heapcrm_cl"
		
	configfile = os.path.join(os.path.expanduser("~"), savefile)
	
	if os.path.isfile(configfile):
		f = open(configfile, 'r')
		configsetting = f.read()
		f.close()
		
		if len(configsetting)>0:
			return configsetting
		else:
			print 'No WebHook URL saved'
			sys.exit()
	else:
		print 'No WebHook URL saved'
		sys.exit()

def callWebHook(myjson,files=[],search='',searchpeople='',history='',stats='',mlist='',mcategory='',muser='',label='',mlabel='',mdate='',mrange=''):
	url = getWebHook()
	values = {}
	
	if len(myjson)>0:
		values['json'] = json.dumps(myjson)
	
	if len(search)>0:
		url = url + "&search=" + urllib.quote(search)
	elif len(searchpeople)>0:
		url = url + "&searchpeople=true&search=" + urllib.quote(searchpeople)
	elif len(history)>0:
		url = url + "&history=true&search=" + urllib.quote(history)
	elif len(stats)>0:
		url = url + "&stats=true&search=" + urllib.quote(stats)
	elif len(mlist)>0:
		url = url + "&list=" + urllib.quote(mlist)
	
	if len(mcategory)>0:
		 url = url + "&category=" + urllib.quote(mcategory)
	if len(muser)>0:
		 url = url + "&user=" + urllib.quote(muser)
	if len(mlabel)>0:
		 url = url + "&mylabel=" + urllib.quote(mlabel)
	if len(label)>0:
		 url = url + "&label=" + urllib.quote(label)
	if len(mdate)>0:
		 url = url + "&date=" + urllib.quote(mdate)
	if len(mrange)>0:
		 url = url + "&range=" + urllib.quote(mrange)
	
	
	if len(files)>0:
		register_openers()
		for ins, s in enumerate(files):
			values['file_'+str(ins)] = open(s,'rb')
		
		data, headers = multipart_encode(values)
		req = urllib2.Request(url,data,headers)
	else:
		data = urllib.urlencode(values)
		req = urllib2.Request(url,data)
	
	print 'Sending data...'
	
	try:
		response = urllib2.urlopen(req)
	except URLError, e:
		print 'Something is wrong with that WebHook'
		print e.read()
		sys.exit()
	else:
		the_page = response.read().strip()
		return the_page
		
def retreaveData(value):
	if len(value.strip())>0 and os.path.isfile(os.path.expanduser(value.strip())):
		f = codecs.open(os.path.expanduser(value.strip()),'r', "utf-8")
		value = f.read()
		f.close()
		return value
	else:
		return value

def fileList(slist):
	flist = slist.strip().split(',')
	listout = []
	for s in flist:
		if len(s.strip())>0 and os.path.isfile(os.path.expanduser(s.strip())):
			if os.path.getsize(os.path.expanduser(s.strip())) < 10240000:
				listout.append(os.path.expanduser(s.strip()))
			else:
				print "File \"" + os.path.expanduser(s.strip()) + "\" not included because it exceeds file limits"
	return listout
	
def createMessage(data):
	mjson = {}
	mjson['title'] = retreaveData(data.title.strip())
	mjson['body'] = retreaveData(data.body.strip())	
	if data.simulate == True:
		mjson['simulate'] = 'true'
		return callWebHook(mjson)
	else:
		return callWebHook(mjson,fileList(data.file))

def saveString(path,value):
	f = codecs.open(path, 'w', "utf-8")
	f.write(htmlentitydecode(unicode(value, "utf-8")))
	f.close()
	print 'File saved to: ' + path
	
def saveCSV(path,value):
	names = []
	f = codecs.open(path, "w","utf-8")
	csvwriter = UnicodeWriter(f,encoding="utf-8")
	try:
		s = value[0].keys()
	except:
		try:		
			for name in value.keys():
				names.append(htmlentitydecode(name))
			csvwriter.writerow(names)

			newrow = []
			for name in value.keys():
				newrow.append(value[name])
			csvwriter.writerow(newrow)
		except:
			f.write(unicode(value, "utf-8"))				
	else:
		for row in value:
			for name in row.keys():
				try:
					names.index(htmlentitydecode(name))
				except:
					names.append(htmlentitydecode(name))
		csvwriter.writerow(names)

		for row in value:
			newrow = []
			for name in names:
				newrow.append(htmlentitydecode(row.get(name,'')))
			csvwriter.writerow(newrow)
	f.close()
	print 'File saved to: ' + path


def saveTXT(path,value):
	svalue = '';
	for row in value:
		title = ''
		mdate = ''
		association = ''
		calendar = ''
		for name in row.keys():
			if name.lower() == 'date':
				mdate = row.get(name,'').strip()
			elif name.lower() == 'title':
				title = row.get(name,'').strip()
			elif name.lower() == 'association':
				association = row.get(name,'')
			elif name.lower() == 'calendar':
				calendar = row.get(name,'')
		if len(mdate)>0:
			title = title + ' on ' + mdate
		if len(association)>0:
			association = '+' + association.strip().replace(' ','_') + ' '
		if len(calendar)>0:
			calendar = '@' + calendar.strip().replace(' ','_') + ' '
		svalue = svalue + association + calendar + title + myNewLine()
	f = codecs.open(path, 'w', "utf-8")
	f.write(htmlentitydecode(svalue.strip()))
	f.close()
	print 'File saved to: ' + path


def showTXT(value):
	svalue = '';
	for row in value:
		title = ''
		mdate = ''
		association = ''
		calendar = ''
		for name in row.keys():
			if name.lower() == 'date':
				mdate = row.get(name,'').strip()
			elif name.lower() == 'title':
				title = row.get(name,'').strip()
			elif name.lower() == 'association':
				association = row.get(name,'')
			elif name.lower() == 'calendar':
				calendar = row.get(name,'')
		if len(mdate)>0:
			title = title + ' on ' + mdate
		if len(association)>0:
			association = '+' + association.strip().replace(' ','_') + ' '
		if len(calendar)>0:
			calendar = '@' + calendar.strip().replace(' ','_') + ' '
		svalue = svalue + association + calendar + title + myNewLine()	
	print htmlentitydecode(svalue.strip())



def showPersonTXT(value):
	if type(value) is str:
		print value
		return
	svalue = ''
	if type(value) is dict:
		val = []
		val.append(value)
	else:
		val = value
	for row in val:
		myname = ''
		email = ''
		phone = ''
		for name in row.keys():
			if name.lower() == 'name':
				myname = row.get(name,'').strip()
			elif name.lower() == 'email':
				email = row.get(name,'').strip()
			elif name.lower() == 'phone' or name.lower() == 'mobile':
				if len(phone)>0:
					phone = phone + ", " + row.get(name,'')
				else:
					phone = row.get(name,'')
		if len(email)>0 or len(phone)>0:
			myname = myname + ": "
		if len(email)>0 and len(phone)>0:
			email = email + ", "
		svalue = svalue + myname + email + phone + myNewLine()	
	print htmlentitydecode(svalue.strip())

def showStats(value):
	if type(value) is str:
		print value
		return
	svalue = '| Messages | Events | History |' + myNewLine()
	if type(value) is dict:
		val = []
		val.append(value)
	else:
		val = value
	for row in val:
		messages = ''
		events = ''
		history = ''
		for name in row.keys():
			if name.lower() == 'messages':
				messages = row.get(name,'').strip()
			elif name.lower() == 'events':
				events = row.get(name,'').strip()
			elif name.lower() == 'history':
				history = row.get(name,'')
		svalue = svalue + messages.rjust(11) + events.rjust(9) + history.rjust(10) + myNewLine()	
	print htmlentitydecode(svalue.strip())

def showActivity(value):
	if type(value) is str:
		print value
		return
	svalue = '|     Lead     |  Opportunity  |   Customers   |' + myNewLine()
	if type(value) is dict:
		val = []
		val.append(value)
	else:
		val = value
	for row in val:
		lead = ''
		opportunity = ''
		customer = ''
		for name in row.keys():
			if name.lower() == 'lead':
				lead = str(row.get(name,'')).strip()
			elif name.lower() == 'opportunity':
				opportunity = str(row.get(name,'')).strip()
			elif name.lower() == 'customer':
				customer = str(row.get(name,'')).strip()
		svalue = svalue + lead.rjust(15) + opportunity.rjust(16) + customer.rjust(16) + myNewLine()	
	print htmlentitydecode(svalue.strip())



def showHistory(value):
	svalue = ''
	if type(value) is str:
		print value
		return
	svalue = '|       Date       |    Type    | Expected Value |' + myNewLine()
	if type(value) is dict:
		val = []
		val.append(value)
	else:
		val = value
	for row in val:
		mdate = ''
		mtype = ''
		expectedvalue = ''
		for name in row.keys():
			if name.lower() == 'date':
				mdate = row.get(name,'').strip().rjust(19)
			elif name.lower() == 'type':
				mtype = row.get(name,'').strip().rjust(13)
			elif name.lower() == 'expectedvalue':
				expectedvalue = row.get(name,'').strip().rjust(17)
		svalue = svalue + mdate + mtype + expectedvalue + myNewLine()	
	print htmlentitydecode(svalue.strip())
	

def saveTemplateToDisk(path,value):
	svalue = '';
	for row in value:
		subject = ''
		body = ''
		for name in row.keys():
			if name.lower() == 'subject':
				subject = row.get(name,'').strip()
			elif name.lower() == 'body':
				body = row.get(name,'').strip()
		svalue = svalue + "*" + subject + "*" + myNewLine() + myNewLine() + body + myNewLine() + myNewLine()
	f = codecs.open(path, 'w', "utf-8")
	f.write(htmlentitydecode(svalue.strip()))
	f.close()

def showTemplateToDisk(value):
	svalue = '';
	listlen = len(value)
	for row in value:
		subject = ''
		body = ''
		for name in row.keys():
			if name.lower() == 'subject':
				subject = row.get(name,'').strip()
			elif name.lower() == 'body':
				body = row.get(name,'').strip()
		if listlen>1:
			svalue = svalue + subject + myNewLine()
		else:
			svalue = svalue + "*" + subject + "*" + myNewLine() + myNewLine() + body + myNewLine() + myNewLine()
	print htmlentitydecode(svalue.strip())

def tryJsonError(string):
	try:
		return json.loads(string)
	except:
		return string

def searchProspects(search):
	jdata = callWebHook('',[],search.strip())
	return tryJsonError(jdata)

def searchPeople(search):
	jdata = callWebHook('',[],'',search.strip())
	return tryJsonError(jdata)
	
def searchHistory(search):
	jdata = callWebHook('',[],'','',search.strip())
	return tryJsonError(jdata)

def searchStats(search):
	jdata = callWebHook('',[],'','','',search.strip())
	return tryJsonError(jdata)

def searchLists(search,mcategory='',muser='',label='',mlabel='',mdate='',mrange=''):
	jdata = callWebHook('',[],'','','','',search.strip(),mcategory,muser,label,mlabel,mdate,mrange)
	return tryJsonError(jdata)

def processOptions(string,mydic):
	s = string.strip().split(',')
	for op in s:
		args = op.strip().split('=',1)
		if len(args) == 2:
			if len(args[0].strip())>0 and len(args[1].strip())>0:
				mydic[args[0].strip()] = args[1].strip()
	return mydic

def processCategories(string):
	s = string.strip().split(',')
	li = []
	for ss in s:
		if len(ss.strip())>0:
			li.append(ss.strip())
	return li
	
def createPerson(data):
	mjson = {}
	mjson['name'] = retreaveData(data.name.strip())
	mjson['title'] = retreaveData(data.position.strip())
	mjson['email'] = retreaveData(data.email.strip())	
	mjson['phone'] = retreaveData(data.phone.strip())
	mjson['mobile'] = retreaveData(data.mobile.strip())
	mjson['fax'] = retreaveData(data.fax.strip())
	mjson['address'] = retreaveData(data.address.strip())
	mjson['city'] = retreaveData(data.city.strip())
	mjson['state'] = retreaveData(data.state.strip())
	mjson['zip'] = retreaveData(data.zip.strip())
	mjson['country'] = retreaveData(data.country.strip())
	mjson['website'] = retreaveData(data.website.strip())
	mjson['notes'] = retreaveData(data.notes.strip())
	mjson['value'] = retreaveData(data.value.strip())
	mjson['probability'] = retreaveData(data.probability.strip())
	mjson['moreinfo'] = retreaveData(data.moreinfo.strip())
	mjson['type'] = retreaveData(data.type.strip())
	mjson['template'] = retreaveData(data.template.strip())
	mjson['categories'] = processCategories(retreaveData(data.categories.strip()))
	mjson['labels'] = processCategories(retreaveData(data.labels.strip()))
	mjson = processOptions(retreaveData(data.custom.strip()),mjson)
	return callWebHook(mjson)	

def createTemplate(data):
	mjson = {}
	mjson['subject'] = retreaveData(data.subject.strip())
	mjson['body'] = retreaveData(data.content.strip())
	return callWebHook(mjson)

def main():
	didsomething = False
	mystring = ' '
	mycsv = ''
	desc = 'HeapCL allows you to interact with your CRM directly from the command line.  Use the following options to create messages, people, prospects and e-mail templates.  Additionally, use the search features to retrieve data and optionally save it to a file.'
	p = optparse.OptionParser(description=desc)
	utilities = optparse.OptionGroup(p, 'Utility Options')
	utilities.add_option('--webhook', '-w', dest="webhook", help="Define the webhook to use for all transactions", default='', metavar='"<Valid WebHook>"')
	utilities.add_option('--save', '-s', dest="savefile", help="Save output to a file", default='', metavar='"<File Path>"')
	utilities.add_option('--text', dest="stext", action="store_true", default=False, help="Change screen output to text")
	utilities.add_option('--version', dest="version", action="store_true", default=False, help="Check if this is the current version of HeapCL")
	
	messages = optparse.OptionGroup(p, 'Inserting Messages Options')
	messages.add_option('--title', '-t', dest="title", help="When defining a message, set the title", default='', metavar='"<Title or File Path>"')
	messages.add_option('--body', '-b', dest="body", help="When defining a message, set the body", default='', metavar='"<Body or File Path>"')
	messages.add_option('--files', '-f', dest="file", help="Comma seperated list of files to attach when creating a message", default='', metavar='"<File Path>, <File Path>"')
	messages.add_option("--simulate", action="store_true", dest="simulate", default=False, help="Evaluates the message body for email commands but doesn't create the final message")
	
	people = optparse.OptionGroup(p, 'Inserting People Options')
	people.add_option('--name', '-n', dest="name", help="When defining a person, set the name", default='', metavar='"<Name or File Path>"')
	people.add_option('--position', dest="position", help="When defining a person, set the title/position", default='', metavar='"<Title/Position or File Path>"')
	people.add_option('--email', '-e', dest="email", help="When defining a person, set the email address(es)", default='', metavar='"<E-Mail(s) or File Path>"')
	people.add_option('--phone', '-p', dest="phone", help="When defining a person, set the phone number(s)", default='', metavar='"<Phone(s) or File Path>"')
	people.add_option('--mobile', '-m', dest="mobile", help="When defining a person, set the mobile number(s)", default='', metavar='"<Mobile(s) or File Path>"')
	people.add_option('--fax', dest="fax", help="When defining a person, set the fax number(s)", default='', metavar='"<Fax(s) or File Path>"')
	people.add_option('--address','-a', dest="address", help="When defining a person, set the address", default='', metavar='"<Address or File Path>"')
	people.add_option('--city','-c', dest="city", help="When defining a person, set the city", default='', metavar='"<City or File Path>"')
	people.add_option('--state', dest="state", help="When defining a person, set the state", default='', metavar='"<State or File Path>"')
	people.add_option('--zip','-z', dest="zip", help="When defining a person, set the zip", default='', metavar='"<Zip or File Path>"')
	people.add_option('--country', dest="country", help="When defining a person, set the country", default='', metavar='"<Country or File Path>"')
	people.add_option('--website', dest="website", help="When defining a person, set the website(s)", default='', metavar='"<Website(s) or File Path>"')
	people.add_option('--notes', dest="notes", help="When defining a person, set the notes section", default='', metavar='"<Notes or File Path>"')
	people.add_option('--categories', dest="categories", help="When defining a person, set a comma seperated list of categories", default='', metavar='"<Category One>, <Category Two>"')
	people.add_option('--custom', dest="custom", help="When defining a person, set a comma seperated list of custom values", default='', metavar='"<Field1>=<Value One>, <Field2>=<Value Two>"')
	
	prospects = optparse.OptionGroup(p, 'Additional Prospect Options')
	prospects.add_option('--value','-v', dest="value", help="When defining a prospect, set the value", default='', metavar='"<Number >=0 >"')
	prospects.add_option('--probability', dest="probability", help="When defining a prospect, set the probability", default='', metavar='"<Number 0-1>"')
	prospects.add_option('--moreinfo', dest="moreinfo", help="When defining a prospect, set the more info section", default='', metavar='"<More Info or File Path>"')
	prospects.add_option('--type', dest="type", help="When defining a prospect, set the type (e.g.'lead')", default='', metavar='"<Prospect Type>"')
	prospects.add_option('--labels', dest="labels", help="When defining a labels, set a comma seperated list of labels", default='', metavar='"<Label One>, <Label Two>"')
	prospects.add_option('--template', dest="template", help="When defining a prospect, fire an event template", default='', metavar='"<Event Template Name>"')
	
	templates = optparse.OptionGroup(p, 'Create E-Mail Templates')
	templates.add_option('--subject', dest="subject", help="When defining an e-mail template, set the subject line", default='', metavar='"<Subject or File Path>"')
	templates.add_option('--content', dest="content", help="When defining an e-mail template, set the body/content", default='', metavar='"<Body/Content or File Path>"')
	
	search = optparse.OptionGroup(p, 'Search and Retrieve Data')
	search.add_option('--search', dest="search", help="Search prospects", default='', metavar='"<Prospect Search Term>"')
	search.add_option('--searchpeople', dest="searchpeople", help="Search people", default='', metavar='"<Person Search Term>"')
	search.add_option('--history', dest="history", help="Show a prospect's history", default='', metavar='"<Prospect Name>"')
	search.add_option('--stats', dest="stats", help="Show a prospect's statistics", default='', metavar='"<Prospect Name>"')
	search.add_option('--list', dest="lists", help="Request a list, currently supports 'emailtemplates', 'events', 'messages', 'pipeline' and 'activity'; you can also specify an association (events and messages) or subject (email templates) to filter the list", default='',  metavar='"<List Item>"')
	search.add_option('--label', dest="label", help="When requesting the pipeline or activity, you can specify a label to filter on", default='',  metavar='"<Label>"')
	search.add_option('--mylabel', dest="mylabel", help="When requesting the pipeline or activity, you can specify one of your labels to filter on", default='',  metavar='"<My Label>"')
	search.add_option('--category', dest="category", help="When requesting the pipeline or activity, you can specify a category to filter on", default='',  metavar='"<Category>"')
	search.add_option('--user', dest="user", help="When requesting the pipeline or activity, you can specify an user to filter on", default='',  metavar='"<User Name>"')
	search.add_option('--date', dest="date", help="When requesting activity, you can specify the date of the activity", default='',  metavar='"<Date>"')
	search.add_option('--range', dest="range", help="When requesting activity, you can specify range: currently supports month, year and week", default='week',  metavar='"<Range>"')
	p.add_option_group(utilities)
	p.add_option_group(messages)
	p.add_option_group(people)
	p.add_option_group(prospects)
	p.add_option_group(templates)
	p.add_option_group(search)
	
	(options, arguments) = p.parse_args()
	
	if len(options.webhook.strip())>0:
		didsomething = True
		mystring = saveWebHook(options.webhook.strip())
	
	if len(options.title.strip())>0 and len(options.name.strip())==0:	
		didsomething = True
		mystring = createMessage(options)
	elif len(options.subject.strip())>0:
		didsomething = True
		mystring = createTemplate(options)
	elif len(options.name.strip())>0:
		didsomething = True
		mystring = createPerson(options)
	
	if len(options.search.strip())>0:
		didsomething = True
		mycsv = searchProspects(options.search.strip())
		
	if len(options.searchpeople.strip())>0:
		didsomething = True
		mycsv = searchPeople(options.searchpeople.strip())
	
	if len(options.history.strip())>0:
		didsomething = True
		mycsv = searchHistory(options.history.strip())
		
	if len(options.stats.strip())>0:
		didsomething = True
		mycsv = searchStats(options.stats.strip())
	
	if len(options.lists.strip())>0:
		didsomething = True
		if options.lists.strip().lower()[0:8]=='pipeline' or options.lists.strip().lower()[0:8]=='activity':
			mycsv = searchLists(options.lists.strip(), options.category.strip(),options.user.strip(),options.label.strip(),options.mylabel.strip(),options.date.strip(),options.range.strip())
		else:
			mycsv = searchLists(options.lists.strip())
			
	if len(mystring.strip())>0 and len(options.savefile.strip())>0 and os.path.abspath(os.path.expanduser(options.savefile.strip())) != False:
		saveString(os.path.abspath(os.path.expanduser(options.savefile.strip())),mystring)
	elif len(mystring.strip())>0:
		print mystring
		
	if len(mycsv)>0 and len(options.savefile.strip())>0 and os.path.abspath(os.path.expanduser(options.savefile.strip())) != False and options.savefile.strip().lower()[-4:]=='.txt' and options.lists.strip().lower()[0:6]=='events':
		saveTXT(os.path.abspath(os.path.expanduser(options.savefile.strip())),mycsv)
	elif len(mycsv)>0 and len(options.savefile.strip())>0 and os.path.abspath(os.path.expanduser(options.savefile.strip())) != False and options.savefile.strip().lower()[-4:]=='.txt' and (options.lists.strip().lower()[0:14]=='emailtemplates' or options.lists.strip().lower()[0:8]=='messages'):
		saveTemplateToDisk(os.path.abspath(os.path.expanduser(options.savefile.strip())),mycsv)
	elif len(mycsv)>0 and len(options.savefile.strip())>0 and os.path.abspath(os.path.expanduser(options.savefile.strip())) != False:
		saveCSV(os.path.abspath(os.path.expanduser(options.savefile.strip())),mycsv)
	elif len(mycsv)>0 and options.stext==True and options.lists.strip().lower()[0:6]=='events':
		showTXT(mycsv)
	elif len(mycsv)>0 and options.stext==True and (options.lists.strip().lower()[0:14]=='emailtemplates' or options.lists.strip().lower()[0:8]=='messages'):
		showTemplateToDisk(mycsv)
	elif len(mycsv)>0 and options.stext==True and (options.lists.strip().lower()[0:8]=='pipeline' or options.lists.strip().lower()[0:8]=='activity'):
		showActivity(mycsv)	
	elif len(mycsv)>0 and options.stext==True and (len(options.search.strip())>0 or len(options.searchpeople.strip())>0):
		showPersonTXT(mycsv)
	elif len(mycsv)>0 and options.stext==True and len(options.stats.strip())>0:
		showStats(mycsv)
	elif len(mycsv)>0 and options.stext==True and len(options.history.strip())>0:
		showHistory(mycsv)
	elif len(mycsv)>0:
		print mycsv

	if options.version == True:
		didsomething = True
		checkVersion()
		
	if didsomething==False:
		print "Please specify at least a few parameters, otherwise I can't do much"

if __name__ == '__main__':
	main()