#!/usr/bin/env python

import sys
import os
import errno
import make_screen

ROOT = "/idr/filesets/idr0012-fuchs-cellmorph/downloaded/primary/source/www.ebi.ac.uk/huber-srv/cellmorph/source"
SCREENS_DIR = os.path.join(os.pardir, "screens")
PLATES_DIR = os.path.join(os.pardir, "screenA/plates")
REL_SCREENS_DIR = "idr0012-fuchs-cellmorph/primary/raw/screens"


def main(argv):
    try:
        os.makedirs(SCREENS_DIR)
        os.makedirs(PLATES_DIR)
    except OSError as e:
        if e.errno == errno.ENOENT:
            pass
    basenames = os.listdir(ROOT)
    with open("stats.txt", "w") as fo:
        for bn in basenames:
            d = os.path.join(ROOT, bn)
            if not os.path.isdir(d):
                continue
            n_wells = sum(1 for _ in os.listdir(d)
                          if os.path.isdir(os.path.join(d, _)))
            fo.write("%s\t%d\n" % (d, n_wells))
            screen_fn = os.path.join(SCREENS_DIR, "%s.screen" % bn)
            make_screen.main(["dummy", d, "-o", screen_fn, "-p", bn])
            plate_fn = os.path.join(PLATES_DIR, bn)
            with open(plate_fn, "w") as plate_file:
                plate_file.write("%s/%s.screen\n" % (REL_SCREENS_DIR, bn))


if __name__ == "__main__":
    main(sys.argv)
