import os, sys, json
from simperium.core import Api as SimperiumApi

appname = 'chalk-bump-f49' # Simplenote
token = os.environ['TOKEN']
backup_dir = sys.argv[1] if len(sys.argv) > 1 else (os.path.join(os.environ['HOME'], "Dropbox/SimplenoteBackups"))
print "Starting backup your simplenote to: %s" % backup_dir
if not os.path.exists(backup_dir):
    print "Creating directory: %s" % backup_dir
    os.makedirs(backup_dir)

api = SimperiumApi(appname, token)
#print token
notes = api.note.index(data=True)
for note in notes['index']:
    #if the note has a single tag, put it into a subdirectory named as the tag
    if len(note['d']['tags'])==1:
        tag = note['d']['tags'][0]
    else:
        tag = ''
    dir_path = os.path.join(backup_dir, tag)
    try:
        os.makedirs(dir_path)
    except OSError as e:
        if e.errno == 17:
            # the subdir already exists
            pass

    path = os.path.join(dir_path, note['id'] + '.txt')
    #print path
    with open(path, "w") as f:
        # print json.dumps(note, indent=2)
        #f.write("id: %s\n" % note['id'])
        f.write(note['d']['content'].encode('utf8'))
        f.write("\n")
        f.write("Tags: %s\n" % ", ".join(note['d']['tags']).encode('utf8'))
    os.utime(path,(note['d']['modificationDate'],note['d']['modificationDate']))

print "Done: %d files." % len(notes['index'])

@@ -527,16 +527,237 @@
 ndex'%5D:%0A
+trashed = 0%0A    dir_path = backup_dir%0A    #if the note was trashed, put it into a 'TRASH' subdirectory%0A    if note%5B'd'%5D%5B'deleted'%5D== True:%0A        dir_path = os.path.join(dir_path, 'TRASH')%0A        trashed = trashed + 1%0A%0A
     #if 
@@ -873,107 +873,65 @@
     
-tag = note%5B'd'%5D%5B'tags'%5D%5B0%5D%0A    else:%0A        tag = ''%0A    dir_path = os.path.join(backup_dir, tag
+dir_path = os.path.join(dir_path, note%5B'd'%5D%5B'tags'%5D%5B0%5D
 )%0A
+%0A
     
@@ -1408,24 +1408,208 @@
 de('utf8'))%0A
+        # record pinned notes and whatever else%0A        if len(note%5B'd'%5D%5B'systemTags'%5D)%3E0:%0A            f.write(%22System tags: %25s%5Cn%22 %25 %22, %22.join(note%5B'd'%5D%5B'systemTags'%5D).encode('utf8'))%0A
     os.utime
@@ -1703,29 +1703,45 @@
 iles
+ (%25d in TRASH)
 .%22 %25 
+(
 len(
-notes%5B'index'%5D
+index), trashed
 )%0A

Put deleted notes in a trash subdirectory