#!/usr/bin/env python
"""
Usage: fcsplot in_file.fcs out_file.png
Author: James Wettenhall <james.wettenhall@monash.edu>
"""
import sys
import os
import array
from rpy2.robjects.packages import importr
from rpy2.robjects import StrVector

if len(sys.argv) < 3:
    print "Usage: fcsplot in_file.fcs out_file.png"
    sys.exit(1)

graphics = importr('graphics')
grdevices = importr('grDevices')
base = importr('base')
flowCore = importr('flowCore')

flowSet = flowCore.read_flowSet(files=sys.argv[1], emptyValue=False,
                                ignore_text_offset=True)
frameName = base.ls(envir=flowSet.do_slot("frames"))
flowFrame = base.get(frameName, envir=flowSet.do_slot("frames"))
colNames = tuple(flowSet.do_slot("colnames"))

flowViz = importr('flowViz')

grdevices.png(file=sys.argv[2])

if 'FSC' in colNames and 'SSC' in colNames:
    flowViz.flowPlot(flowFrame, plotParameters=StrVector(['FSC', 'SSC']),
                     main=os.path.basename(sys.argv[1]))
elif 'FSC-A' in colNames and 'SSC-A' in colNames:
    flowViz.flowPlot(flowFrame, plotParameters=StrVector(['FSC-A', 'SSC-A']),
                     main=os.path.basename(sys.argv[1]))
elif 'FSC' in colNames and 'SCC' in colNames:
    flowViz.flowPlot(flowFrame, plotParameters=StrVector(['FSC', 'SCC']),
                     main=os.path.basename(sys.argv[1]))
else:
    raise Exception("Couldn't find FSC and SSC columns for plotting "
                    "preview image.")
grdevices.dev_off()
