import os
import hashlib
from tosec.models import Rom, Game
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    args = '<folder>'
    help = 'Scan a folder for TOSEC roms'

    def handle(self, *args, **kwargs):
        directory = args[0]
        dest = os.path.join(directory, 'TOSEC')
        if not os.path.exists(dest):
            os.makedirs(dest)
        self.stdout.write("Scanning %s" % directory)
        filenames = os.listdir(directory)
        total_files = len(filenames)
        tosec_sets = {}  # Store TOSEC sets with number of found roms
        for index, filename in enumerate(filenames, start=1):
            abspath = os.path.join(directory, filename)
            if not os.path.isfile(abspath):
                continue
            md5sum = hashlib.md5(open(abspath).read()).hexdigest()
            try:
                rom = Rom.objects.get(md5=md5sum)
            except Rom.DoesNotExist:
                continue
            set_name = rom.game.category.name
            if set_name in tosec_sets:
                tosec_sets[set_name] += 1
            else:
                tosec_sets[set_name] = 1
            self.stdout.write("[{} of {}] Found {}".format(index,
                                                           total_files,
                                                           rom.name))
            new_path = os.path.join(dest, rom.name)
            os.rename(abspath, new_path)

        for set_name in tosec_sets:
            set_size = Game.objects.filter(category__name=set_name).count()
            self.stdout.write("{}: imported {} of {} games".format(
                set_name, tosec_sets[set_name], set_size
            ))

@@ -18,16 +18,49 @@
 hashlib%0A
+from optparse import make_option%0A
 from tos
@@ -231,16 +231,248 @@
 EC roms'
+%0A    option_list = BaseCommand.option_list + (%0A        make_option('--destination', action='store', type=%22str%22),%0A        make_option('--create-set-folders', action='store_true',%0A                    dest=%22create_set_folders%22),%0A%0A    )
 %0A%0A    de
@@ -499,13 +499,14 @@
 , **
-kwarg
+option
 s):%0A
@@ -547,16 +547,83 @@
   dest =
+ options.get('destination')%0A        if not dest:%0A            dest =
  os.path
@@ -715,16 +715,75 @@
 s(dest)%0A
+        create_set_folders = options%5B'create_set_folders'%5D%0A
         
@@ -1765,19 +1765,282 @@
         
-new
+if create_set_folders:%0A                set_path = os.path.join(dest, set_name)%0A                if not os.path.exists(set_path):%0A                    os.mkdir(set_path)%0A                dest_path = os.path.join(set_path, rom.name)%0A            else:%0A                dest
 _path = 
@@ -2103,11 +2103,12 @@
 th, 
-new
+dest
 _pat

Add options for tosec scan destination