#!/bin/csh
####################################
# theTab = table name
# Argument is P=period
# Vgraph is "gif" "ps" or "txt"
####################################
set debug = 0

if ($debug) then
    touch /tmp/Vplot
    (echo ""; echo "----`date`") >> /tmp/Vplot
    printenv | sort >> /tmp/Vplot
    @ i = 0
    while ($i < $#argv)
        @ i += 1
        echo "....Arg#$i => '$argv[$i]'" >> /tmp/Vplot
    end
endif

#################################################################
# Get the Arguments: tab and Period
#################################################################
set Star = `echo $theTab | acut -d\/ -f1 | tr '_' ' '| trim `
set File = `echo $theTab | acut -d\/ -f2 `

if ("$1" =~ P=*) then
    set P = `echo "$1" | cut -c3-` ; shift
    if (("$P" == 0) && ("$1" == "-x" )) then	### REMOVE Limits 0/1
	if (("$2" == "0") && ("$3" == "1" )) then 
	    shift; shift; shift
	endif
    endif
else
    set P = ""
endif
if ("$P" == "") set P = 0 


#################################################################
# Vgraph not defined ==> just the plot introduction
#################################################################
if (! $?Vgraph) then
    if ($P != 0) then
        set plotx = "-x 0 1"
    else
        set plotx = ""
    endif
    set ploty = ""       # Reverse Y axis
    # These values are superseded by what's contained in $argv

    echo1 "\section*{\object{$Star} light curve (P=$P)} "
    cgigraph -img -ps:"Postscript Figure" -txt:"Data as a Table" -form -htx \
	P=$P -graph $plotx $ploty $argv:q
    exit 0
endif

################################################################
# Actual gif or ps plot (Vgraph contains gif or plot)
################################################################

set  plotarg = \
  "-f 0.0325 -h 0.75 -w 0.75 -u 0.125 -r 0.15 --title-font-size 0.05 -m -1 -S 3"

if ($P != 0) then
    set X = "Phase"
else
    set X = "BJD-2400000"
endif
set Y = 'Flux [ppm]'

asu -data -n- <<====EOQ | gawk -v P=$P 'BEGIN{FS="\t"}\
  /^$/{print; next}\
  /---/ {next}\
  {\
    jd = $1; mag=$2+0;\
    if (P > 0) phase = (jd /P) - int(jd/P) ; \
    else phase = jd-2400000;\
    printf("%.7f %s\n", phase, mag) \
  }' \
| graph -T $Vgraph -C -L "$Star" --pen-colors 1=purple3:2=blue2:3=green3 \
  $plotarg -X $X:q -Y $Y:q $argv:q
-source=$theCat/$File   
-out=NJD, Flux   
====EOQ
exit 0
