import csv
import os.path
import sys


def data(filename, take):
    experiment = os.path.basename(filename).split("_")[0]

    f = open(filename)
    data = csv.reader(f, delimiter="\t")

    headers = data.next()
    keys = ["LOCUS", "CH1I_MEAN", "CH2I_MEAN", "SPOT"]
    idx = zip((headers.index(k) for k in keys), keys)

    result = []
    for row in data:
        rowmap = {h[1]: row[h[0]] for h in idx}

        ch1 = float(rowmap["CH1I_MEAN"])
        ch2 = float(rowmap["CH2I_MEAN"])
        locus = rowmap["LOCUS"]
        spot = int(rowmap["SPOT"])

        if spot % take != 0:
            continue

        balance = (ch1 / (ch1 + ch2) - 0.5) * 2
        rec = {"locus": locus,
               "spot": spot,
               "experiment": experiment,
               "ch1mean": ch1,
               "ch2mean": ch2,
               "balance": balance}
        result.append(rec)

    return result


def run(what=None, take="1"):
    datafiles = ["R12_original.txt",
                 "R16_original.txt",
                 "R1_original.txt",
                 "R21_original.txt",
                 "R28_original.txt",
                 "R30_original.txt",
                 "R3_original.txt",
                 "R6_original.txt",
                 "R8_original.txt",
                 "R15_original.txt",
                 "R17_original.txt",
                 "R20_original.txt",
                 "R24_original.txt",
                 "R2_original.txt",
                 "R36_original.txt",
                 "R42_original.txt",
                 "R7_original.txt"]

    experiments = [x.split("_")[0] for x in datafiles]

    datafiles = [os.path.dirname(os.path.abspath(__file__)) + os.path.sep + f for f in datafiles]

    if what in ["data", "spots"]:
        try:
            take = int(take)
        except ValueError:
            return {"error": "'take' parameter must be an integer"}

    if what == "experiments":
        return experiments
    elif what == "data":
        results = []
        for d in datafiles:
            results += data(d, take)
        return results
    elif what == "spots":
        return [x["spot"] for x in data(datafiles[0], take)]
    else:
        return {"error": "unknown action '%s'" % (what)}


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print >>sys.stderr, "usage: data.py <filename>"
        sys.exit(1)

    print data(sys.argv[1])
