tell application "Evernote"
	try
		set Evernote_Selection to selection
		if Evernote_Selection = {} then
			display dialog "Please select the note to Wikify"
		end if
		set noteName to (title of item 1 of Evernote_Selection)
		set notebookName to (name of notebook of item 1 of Evernote_Selection)
	end try
	
	
	--get plain text of note; from Justin's Veritrope script
	set the_HTML to HTML content of (item 1 of Evernote_Selection)
	set plain_Text to do shell script "echo " & quoted form of the_HTML & space & "| textutil  -convert txt  -stdin -stdout"
	
end tell
set the clipboard to plain_Text

--puts [[brackets]] around all WikiWords in text
Wikify()

--gets new text with [[bracketed]] WikiWords in it and holds as variable
set Bracketed_text to the clipboard

--searches new text and extracts all words within brackets
extractBetween(Bracketed_text, "[[", "]]")

set UnBracketed_text to the clipboard
--puts item in list form
set UnBracketed_list to get words of UnBracketed_text

--delete any duplicate WikiWords in your note from the List
set Unique_UnBracket_list to my remove_duplicates(UnBracketed_list)


--search for and create notes from above list
tell application "Evernote"
	set tid to AppleScript's text item delimiters
	if (not (notebook named noteName exists)) then
		make notebook with properties {name:noteName}
	end if
	set Wiki_list to Unique_UnBracket_list
	set Wiki_list_count to (count items of Wiki_list) as number
	set notebook1 to notebook noteName
	set notebook_search to name of notebook1
	set i to 1
	repeat with i from 1 to Wiki_list_count
		set Wiki_word to item i of Wiki_list
		set matches to find notes "intitle:" & Wiki_word & " " & "tag:Wiki" & " " & "notebook:\"" & notebook_search & "\""
		
		if matches = {} then
			set Wiki_note to create note title Wiki_word with text "" notebook notebook1
			if (not (tag named "Wiki" exists)) then
				make tag with properties {name:"Wiki"}
			end if
			set tag1 to tag "Wiki"
			assign tag1 to Wiki_note
		end if
		if (i > Wiki_list_count) then
			exit repeat
		end if
	end repeat
	
	--All sub notes are now created with appropriate tag and title
	--Next, synchronize to get note links for all wiki notes
	repeat until isSynchronizing is false
	end repeat
	synchronize
	repeat until isSynchronizing is false
	end repeat
	
end tell

--get note links for all wiki notes
tell application "Evernote"
	set Evernote_Selection to every note of notebook1
	set the clipboard to ""
	
	repeat with i from 1 to the count of Evernote_Selection
		set noteURL to note link of item i of Evernote_Selection
		set noteTitle to title of item i of Evernote_Selection
		set theWikiLink to "[" & noteTitle & "]" & "(" & noteURL & ")" & return
		set the clipboard to (the clipboard) & theWikiLink
	end repeat
	set WikiLinks_text to the clipboard
end tell

delay 0.5
--a safety-valve to ensure EN is caught up with our quick data retrieval 

--put [[brackets]] back around the terms from the earlier list that created the new EN notes above; for find and replace later
set the clipboard to ""
repeat with i from 1 to the count of Unique_UnBracket_list
	set itemName to item i of Unique_UnBracket_list
	set theBracketName to "[[" & itemName & "]]" & return
	set the clipboard to (the clipboard) & theBracketName
end repeat

set NewBracketed_text to the clipboard
--this variable has a simple string of your WikiWords

set Bracketed_list to get paragraphs of NewBracketed_text
--this variable puts bracketed text string into list form

set WikiLinks_list to get paragraphs of WikiLinks_text
--this variable takes your list of Wiki-Markdown links and puts into list form

--sort both lists to get in indentical order
set Sorted_Bracketed_list to my simple_sort(Bracketed_list)
set Sorted_WikiLinks_list to my simple_sort(WikiLinks_list)

set EmptyItem to {""}
set FinalBracketed_list to my remove_emptyitem(Sorted_Bracketed_list, EmptyItem)
set FinalWikiLinks_list to my remove_emptyitem(Sorted_WikiLinks_list, EmptyItem)


--find and replace [bracketed] terms in the text with Markdown [title](link)
set the_string to Bracketed_text
set search_strings to FinalBracketed_list
set replace_strings to FinalWikiLinks_list

set ListNumber to the (count of search_strings) as number
set OldDelims to AppleScript's text item delimiters
set the clipboard to ""

considering case
	repeat with i from 1 to ListNumber
		set AppleScript's text item delimiters to item i of search_strings
		set newText to text items of the_string
		set AppleScript's text item delimiters to item i of replace_strings
		set the_string to newText as text
		set the clipboard to the_string
		
		set AppleScript's text item delimiters to OldDelims
	end repeat
end considering

set FinalText to (the clipboard)
--this says it all!

--establish a variable for the line feed (aka LF key)
set LF to ASCII character 10

set FinalText to "Title: " & noteName & LF & "Notebook: " & notebookName & LF & "Keywords: Wiki" & LF & LF & FinalText

--Send Markdown text to TextMate. TextMate must have a clean text document open. 
tell application "TextMate"
	set the clipboard to FinalText
	tell application "System Events"
		keystroke "v" using {command down}
	end tell
end tell


--delete old note
tell application "Evernote"
	set FinalSearch to find notes "intitle:" & "\"" & noteName & "\"" & " " & "-tag:Wiki"
	delete FinalSearch
end tell


(* Here, the user must manually export to EN. To export, you first need to have Multimarkdown installed, and get the improved Markdown2Evernote script from https://gist.github.com/kopischke/1009149. You then set this up as a Command in TextMate. Tim Lockridge has a good set-by-step for the setup here: http://blog.timlockridge.com/blog/2013/02/03/using-textmate-and-markdown-with-evernote-configuring-a-workflow/.
To export, go to  Bundles -> Markdown _> Markdown2Evernote. 

OR 
Try to automate the export with this script
--send Markdown formatted text to Evernote
tell application "TextMate" to activate
menu_click({"TextMate", "Bundles", "Markdown", "Markdown2Evernote"})

*)




(* SUBROUTINES *)

--Wikify handler from Fridemar Pache 
on Wikify()
	
	considering case
		set clb to the clipboard as text
		if clb = "" then
			exit repeat
		end if
		set UpperCaseChars to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
		set LowerCaseChars to "abcdefghijklmnopqrstuvwxyz"
		set Digits to "0123456789"
		set WikiWordChars to UpperCaseChars & LowerCaseChars & Digits
		set countClb to (count characters of clb)
		set i to 1
		set currentChar to character i of clb
		set wikifiedText to ""
		repeat while i ≤ countClb
			-- a substring before a wikiWord
			repeat while i ≤ countClb
				set possibleWikiWord to ""
				set CamelCaseCount to 0
				if (currentChar is in UpperCaseChars) then
					exit repeat
				end if
				set wikifiedText to wikifiedText & currentChar
				set i to i + 1
				if (i > countClb) then
					exit repeat
				end if
				set currentChar to character i of clb
			end repeat
			-- possible WikiWord
			repeat while (i ≤ countClb)
				set possibleWikiWord to possibleWikiWord & currentChar
				if currentChar is in UpperCaseChars then
					set CamelCaseCount to CamelCaseCount + 1
				end if
				set i to i + 1
				if (i > countClb) then
					exit repeat
				end if
				set currentChar to character i of clb
				if not (currentChar is in WikiWordChars) then
					if CamelCaseCount ≥ 2 then
						set WikiWord to possibleWikiWord
						set wikifiedText to wikifiedText & "[[" & WikiWord & "]]"
						exit repeat
					else
						set noWikiWord to possibleWikiWord
						set wikifiedText to wikifiedText & noWikiWord
						exit repeat
					end if
				end if
			end repeat
		end repeat
		set the clipboard to wikifiedText
	end considering
end Wikify


--Search with brackets handler from Yvan Koenig 
to extractBetween(SearchText, startText, endText)
	set tid to AppleScript's text item delimiters
	set AppleScript's text item delimiters to startText
	set liste to text items of SearchText
	set AppleScript's text item delimiters to endText
	set extracts to {}
	repeat with subText in liste
		if subText contains endText then
			copy text item 1 of subText to end of extracts
		end if
	end repeat
	set AppleScript's text item delimiters to " "
	set extracts to extracts as text
	set the clipboard to extracts
	set AppleScript's text item delimiters to tid
end extractBetween

--handler from Qwerty Denzel on MacScripter
on remove_duplicates(this_text)
	set not_list to class of this_text is not list
	if not_list then set this_text to paragraphs of this_text
	set new_text to {}
	repeat with this_line in this_text
		if this_line is not in new_text then set end of new_text to (contents of this_line)
	end repeat
	if not_list then
		set text item delimiters to return
		tell new_text to set new_text to beginning & ({""} & rest)
		set text item delimiters to ""
	end if
	return new_text
end remove_duplicates

--from www.macosautomation.com
on simple_sort(my_list)
	set the index_list to {}
	set the sorted_list to {}
	repeat (the number of items in my_list) times
		set the low_item to ""
		repeat with i from 1 to (number of items in my_list)
			if i is not in the index_list then
				set this_item to item i of my_list as text
				if the low_item is "" then
					set the low_item to this_item
					set the low_item_index to i
				else if this_item comes before the low_item then
					set the low_item to this_item
					set the low_item_index to i
				end if
			end if
		end repeat
		set the end of sorted_list to the low_item
		set the end of the index_list to the low_item_index
	end repeat
	return the sorted_list
end simple_sort

--edited from julifos' script on MacScripter
on remove_emptyitem(start_list, remove_item)
	set theList to start_list
	set itemsToDelete to remove_item
	
	set prevTIDs to AppleScript's text item delimiters
	set AppleScript's text item delimiters to "TRICK"
	set theList to "TRICK" & theList & "TRICK"
	--> theList = "TRICKabTRICKbcTRICKcdTRICKdeTRICK"
	repeat with i in itemsToDelete
		set AppleScript's text item delimiters to "TRICK" & i & "TRICK"
		set theList to theList's text items
		set AppleScript's text item delimiters to "TRICK"
		set theList to theList as text
	end repeat
	
	set AppleScript's text item delimiters to "TRICK"
	--> (theList's text 6 thru -6) = "abTRICKcd"
	set theList to (theList's text 6 thru -6)'s text items
	set AppleScript's text item delimiters to prevTIDs
	return theList
end remove_emptyitem



-- `menu_click`, by Jacob Rus, September 2006
on menu_click(mList)
	local appName, topMenu, r
	
	-- Validate our input
	if mList's length < 3 then error "Menu list is not long enough"
	
	-- Set these variables for clarity and brevity later on
	set {appName, topMenu} to (items 1 through 2 of mList)
	set r to (items 3 through (mList's length) of mList)
	
	-- This overly-long line calls the menu_recurse function with
	-- two arguments: r, and a reference to the top-level menu
	tell application "System Events" to my menu_click_recurse(r, ((process appName)'s ¬
		(menu bar 1)'s (menu bar item topMenu)'s (menu topMenu)))
end menu_click

on menu_click_recurse(mList, parentObject)
	local f, r
	
	-- `f` = first item, `r` = rest of items
	set f to item 1 of mList
	if mList's length > 1 then set r to (items 2 through (mList's length) of mList)
	
	-- either actually click the menu item, or recurse again
	tell application "System Events"
		if mList's length is 1 then
			click parentObject's menu item f
		else
			my menu_click_recurse(r, (parentObject's (menu item f)'s (menu f)))
		end if
	end tell
end menu_click_recurse