#!/bin/csh
# To generate a plot for a Light Curve 
# -- Accept Magnitudes or Colors
# -- Accept list of filters, may include combination with '+' or ','
#Required parameters:
###################################################
# plot     = "Light curve" # beginning of title (default="Light curve")
# Star     = name of star (must exist in Simbad)
# Fall     = list of all filters (e.g. UBVRI or "U;B;V;B+V;R;all")
#            or "a=purple3;b=blue;c=yellow;all"
#            or "U;B;V;b=B;y"
######################################################
# Optional parameters:
#######################################################
# JD0      = 2450000      # Origin of JD
# Pdef     = "1.2345678"  # Default value of period
# Fcol     = "Band"       # name of column containing a Filter
# Flab     = "Tr"         # default label of menu with filter (default = "F")
# Fdef     = "all"        # default filter(s) to plot (default="all")
# Xcol     = "/JD/"       # name of column containing the time (default is *JD*)
# Ycol     = "RV"         # name of column containing the magnitude
# def_err  = 1 # value of the default error (undefined => point not plotted)
# has_err  = 1 # has error bars
# has_lim  = 1 # plot also limits(>) with triangle
# has_file = 1 # the Fall list contains also the associated file(s)
# is_diff  = 1 # differential magnitudes (or relative flux)
# is_flux  = 1 # values are fluxes (not magnitudes); 2: values are velocities
# is_phase = 1 # Values on X are phases (not time)
# no_xlim  = 1 # remove the x range [0/1] (in case of Phase)
# err_max  = 0.01 # Maximal error (points with error > err_max are ignored)
# gfilter  = (awk '/^[0-9 ]/{if($3>0.01)next}{print}') # additional selection
# theFile  = name of the file(s) for the plot (defaut=$theTab or `graph_files`)
# object   = non-standard Simbad name e.g. "\objS{* alf UMi}{\alpha UMi}"
#                or "\vizier{-source=$theCat/$theTab\&ID=$Star}{$Star}"
# title    = non-standard title
# photosys = name of photometric system
# IDcol    = name of column containing the "identifier"
# IDval    = value of the "identifier" (default "$stheStar")
# Xlab     = "Time since burst [h] # label de l'axe des X (dans le cas ou P=0)
# Ylab     = label de l'axe des Y (default: "mag", "Deltamag", "Flux" "Velocity"
#            (when contains Jy or Flux => is_flux=1)
# S1       = symbol (16=filled citcle)
# size_lab = size of the labels (0.05)
# size_symbol = size of the symbols (0.02)
# size_left   = size of the left area  (0.19)
#######################################################
if (0) then
####################################################### Example
set Star = "KH 15D"
set Fall = "VI"
set JD0  = 2450000
set has_err = 1
source $Vroot/lib/graph/lc-mag.csh
exit $status
endif
####################################################### Example (end)

if ($?Mcol) then				# Compatibility Ycol or Mcol
    set Ycol = "$Mcol"
endif
if (! $?Flab) set Flab = "F"
if (! $?has_file) set has_file = 0
set awk_file = $Vroot/lib/graph/lc-mag.awk	# File with AWK script
set tt = /tmp/garg$$

# Accept a menu
set Flist = ""
if ("$1" =~ "LIST_$Flab="*) then
    set Flist = "$1"; shift
else if ("$Fall" =~ *[\;=]* ) then	# List already separated by ;
    set Flist = "LIST_$Flab=$Fall"
    set Fall = `echo "$Fall" | tr ';' ' '`
else if ("$Fall" =~ ? ) then
    set Flist = "LIST_$Flab=$Fall"
else if ("$Fall" =~ *" "*) then
    set Flist = "LIST_$Flab=`echo $Fall|tr ' ' ';'`;all"
else if ("$Fall" != "") then
    set Fall = "`echo $Fall|sed 's/\(.\)/\1;/g'`all"
    set Flist = "LIST_$Flab=$Fall"
endif

set F = ""
if ("$1" =~ "$Flab="*) then
    set F = `echo "$1" | acut -d= -f2-`; shift
endif
echo2 "#lc-mag: F=$F"
if (("$F" == "") && ($has_file)) then
    if ($?theFile) then
	set f = `echo $theFile | acut -d. -f1`
    else
        set f = $theTab
    endif
    graph_item -F "$f" "$Fall" > $tt; set F = "`cat $tt`"; rm -f $tt
    echo2 "#...graph_item -F '$f' '$Fall' => F=$F"
endif
if ("$F" == "") then
    if ($?Fdef) then
        set F = "$Fdef"
    else if ("$Fall" =~ *all) then
        set F = "all"
    else 
        set F = "$Fall"
    endif
endif

# Period
if ("$1" =~ P=*) then
    set P = `echo "$1" | cut -c3-` ; shift
    # A valid period must contain at least one non-zero digit
    if ("$P" !~ *[1-9]*) then
        set P = ""		# No period at all
        if ("$1" == "-x" ) then ### REMOVE Limits 0/1
            if (("$2" == "0") && ("$3" == "1" )) then
                shift; shift; shift
            endif
	endif
    endif
else if ($?Pdef) then
    set P = "$Pdef"
else
    set P = ""
endif
if ("$P" == "") set P = 0

# Filter in a dedicated column ? 
if (! $?Fcol) set Fcol = ''
# Magnitude in a dedicated column ? 
if (! $?Ycol) then
    set Ycol = ''
    if ("$Flab" == Y) set Ycol = "$F"
endif
# Time in a dedicated column ? 
if (! $?Xcol) set Xcol = ''
# Differential magnitude ? 
if (! $?is_diff) set is_diff = 0
# Flux, velocity or magnitude ?
if (! $?is_flux) then
    set is_flux = 0
    set term = ""
    if ($?Ylab) then
	set term = "$Ylab"
    else if ($?plot) then
        set term = "$plot"
    endif
    if ("$term" != "") then
        if ("$term" =~ *[Ff]lux*) set is_flux = 1
        if ("$term" =~ *[Vv]el*)  set is_flux = 2
    endif
endif
if (! $?is_phase) then
    set is_phase = 0
else
    set P = 0
endif

# Beginning of title
if (! $?plot) then
    set plot = "Light curve"
    if ($is_flux == 2) set plot = "Velocity curve"
endif
# Phase diagram ?
if (! $?no_xlim) then
    set no_xlim = 0
    if ("$plot" =~ *[Tt]ransit*) set no_xlim = 1
endif
# has_file: choice special argument for graph_title etc
set graph_opt = ()
#if ($has_file && ("$F" != "") && ("$F" != "all")) then
#    set graph_opt = (-F "$F")
#endif
#echo2 "#...graph_opt=$graph_opt"
## 

#################################################################
# Vgraph not defined ==> just the plot introduction
##################################################################

if (! $?Vgraph) then

    set Parg = "P=$P"
    if ($is_phase) set Parg = ()
    #set plotx = ""
    #if (($P != 0) && ($no_xlim == 0)) set plotx = "-x 0 1"
    #set ploty = "-y - - -" 	# Reverse Y axis
    #if ($is_flux) set ploty = ""
    if ($?title) then		# Title is defined...
	 set Pt = ""
	 if ("$title" !~ *"(P"*")*") then
	     if ("$P" != "0") set Pt = "(P=$P)"
	 endif
         echo1 "\section*{$title $Pt}"
    else
        set atit = ""		# Additional element of title
	if ($?photosys) then
	    set atit = "$photosys"
	endif
        if ($is_diff) then
	    set diff = "diff."
	    if ($is_flux == 1) set diff = "rel."
	    set atit = "$atit $diff"
	endif
	#echo1 "Fall=$Fall; \verb!`which graph_title`;`graph_title '$Fall'`!"
	if (! $?object) then
	    set object = "\object{$Star}"
	endif
	set pref = "for"
        if ("$Flab" == "F") set pref = "in"	# Filters: in
	#echo1 '\begin{verbatim}'
        echo1 -n "\section*{$plot of $object $pref $atit "
	#echo1 "[F=$F] graph_title $graph_opt:q '$Fall:q'"
	graph_title $graph_opt:q $Fall:q | tee /tmp/graph_title
	if($#Parg>0) echo1 "($Parg)"; 
	echo1 "}"
        #echo1 "`graph_title $Fall:q` (P=$P)}"
    endif
    #echo2 "#...cgigraph -form -htx '$Flist' $Flab='$F' P=$P"
    if ($?subtitle) then
        echo1 "$subtitle"
    endif
    if ($?caption) then
        set cap = "-cap:$caption"
    else
        set cap = ( )
    endif
    cgigraph -img -ps:"Postscript Figure" -txt:"Data as a Table" $cap:q \
        -form -htx "$Flist" $Flab="$F" $Parg:q -graph $argv:q
        #"$Flist" $Flab="$F" $Parg:q -graph $plotx $ploty $argv:q
    #ls -lL `which graph_title`
    if ($?postface) then
        echo1 "$postface"
    endif
    exit 0
endif

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

#set verbose
# S1 = symbol (16)
# size_lab = size of the labels (0.05)
# size_symbol = size of the symbols (0.02)
# size_left   = size of the left area  (0.19)

if (! $?S1) set S1 = 16
if (! $?size_lab) set size_lab = 0.05
if (! $?size_symbol) set size_symbol = 0.02
if (! $?size_left) set size_left = 0.19
#set  plotarg = "-f 0.05 -h 0.85 -w 0.75 -u 0.125 -r 0.19 -m -1 -S 16 0.02"
set  plotarg = ( -f $size_lab -h 0.85 -w 0.75 -u 0.125 -r $size_left -m -1 \
     -S 16 $size_symbol )

set opt = ()
if (! $?def_err)  set def_err =  ""
if (! $?has_err)  set has_err =  0
if (! $?has_lim)  set has_lim =  0
if (! $?err_max)  set err_max = 0	# Maximal error
if (! $?gfilter)  set gfilter = cat	# Filter the results
if ($has_err) then
    set opt = ( $opt:q -I e )
    set has_err = 1
else
    set has_err = 0
endif
if (! $?JD0) set JD0 = 2450000

if ($P != 0) then
    set X = "Phase"
    set iJD = 0
else if ($?Xlab) then
    set X = "$Xlab"
else if ($is_phase) then
    set X = "Phase"
else if ($?Xcol) then
    set X = "JD-$JD0"
    if ("$Xcol" =~ *JD) set X = "$Xcol-$JD0"
else
    set X = "JD-$JD0"
endif
if ($?Ylab) then
    set Y = "$Ylab"
else if ($is_flux == 1) then
    set Y = "Flux"
    if ($is_diff) set Y = "Flux (relative)"
else if ($is_flux == 2) then
    set Y = "Velocity"
    if ($is_diff) set Y = "Velocity (relative)"
else
    set Y = 'mag'
    if ($is_diff) set Y = '\*Dm [mag]'
endif

if (JD0 =~ *00000) then
    set iJD = 3
    set JD0 = 0
else if (JD0 =~ *0000) then
    set iJD = 4
    set JD0 = 0
else if (JD0 =~ *000) then
    set iJD = 5
    set JD0 = 0
else if (JD0 =~ *00) then
    set iJD = 6
    set JD0 = 0
else 
    set iJD = 0
endif

# theTab may designate several tables
if ($?theFile) then
    if ("$theFile" =~ *.dat*) then
       set files = ( $theFile:q )
    else if ($#theFile >= 1) then
       if (-r $theFile[1]) then
           set files = ( $theFile:q )
	else
	    set files = \
	    `echo $theFile | gawk '{for(i=1;i<=NF;i++) print $i ".dat"}'`
	endif
    else
       set files = `echo $theFile | gawk '{for(i=1;i<=NF;i++) print $i ".dat"}'`
    endif
else if ($has_file) then
    #echo2 "#-----------graph_file:"
    #graph_file $graph_opt:q "$Fall" | cat2 
    # graph_file returns the name of the file(s)
    if (("$F" != "") && ("$F" != "all")) set graph_opt = (-F "$F")
    graph_file $graph_opt:q "$Fall" > $tt; set files = `cat $tt`; rm -f $tt
    echo2 "#...graph_file  $graph_opt:q <$Fall> ==> files= $files"
    if ("$files" !~ *.*) then # No extension => add .dat
        set files = `echo $files | gawk '{for(i=1;i<=NF;i++) print $i ".dat"}'`
    endif
    if (! $?graph_color) then
        graph_color "$Fall" > $tt; 
	set graph_color = `cat $tt`; 
	rm -f $tt
    endif
else
    set files = `echo $theTab | gawk '{for(i=1;i<=NF;i++) print $i ".dat"}'`
endif

# Accept FITS or table
#set TBcom = (tabmap  -par -null '') # [does not work]
#if ("$files" =~ *.fit* ) set TBcom = ( fits2a -head -par -c )
# Filtering with IDcol/IDval
set IDcom = cat
set IDarg = ()
if ($?IDcol) then
    set IDcom = "pargrep"
    if (! $?IDval) set IDval = "$Star"
    # Accept IDval as a regular expression if surrounded by / % = 
    echo "%$IDcol $IDval" | trim | gawk -v q="'" '\
      BEGIN{REc="/%="; printf "set IDarg = %s", q; s="[].*\\+"; \
       Q[" "] = "  *"; Q[q] = q "\"" q "\"" q; }\
      { printf "%s",substr($0,1,1); c=substr($2,1,1); \
        if((index(REc,c)>0)&&(substr($NF,length($NF),1)==c)) Q[c]=""; \
	else { for(i=1;i<=length(s);i++) { c=substr(s,i,1); Q[c] = "[" c "]" }}\
        for(i=2;i<=length;i++) { c=substr($0,i,1); \
	if (c in Q) printf "%s", Q[c]; else printf "%s", c }\
	printf "\\n%s\n", q }' > $tt
    echo2 "#===IDval=$IDval => `cat $tt`"
    source $tt; rm -f $tt
else
    set IDcol = ""
endif

#m=index(Fall,c); if((F!="all")&&(index(F,c)==0)) return; # Color not asked
#echo2 "#...files=./$files"
if ($?theFile) then
    echo2 "#...theFile=./$theFile"
else
    echo2 "#...theFile=(undef)"
endif
if (! $?graph_color) then
    graph_color $graph_opt "$Fall" > $tt
    set graph_color = `cat $tt`; rm -f $tt
    echo2 "#...graph_color $graph_opt '$Fall' ==> $graph_color"
else if ($graph_color !~ *=* ) then
    set c = $graph_color
    set graph_color = "1=${c}:2=${c}:3=${c}:4=${c}:5=${c}"
endif

### Decide only here the plot
set plotx = ""
if (($P != 0) && ($no_xlim == 0)) set plotx = "-x 0 1"
set ploty = "-y - - -" 	# Reverse Y axis
if ($is_flux) set ploty = ""
###

#if ("$files" =~ *.dat* ) set files = "./$files"
set X4map = "$Xcol"
if ("$X4map" =~ /*/) set X4map = ""
echo2 "#...tabmap  -par -null '' '$Fcol $X4map *' $files | $IDcom $IDarg:q "
echo2 "#...|graph ...  --pen-colors $graph_color"
if ($#IDarg>0) echo2 "#...IDargx$#IDarg = $IDarg:q"
#set perm = "`graph_perm '$Fall'`"
graph_perm $Fall:q > $tt; set perm = "`cat $tt`"; rm -f $tt
#tabmap -par -data -null "" "$Fcol *" -i "%#file" $files 
tabmap  -par -null '' "$Fcol $X4map *" -i "%#file" $files \
| trim \
| tee /tmp/lc-mag.all\
| $IDcom $IDarg:q \
| tee /tmp/lc-mag.in \
| gawk -v P=$P -v F="$F" -v Fall="$Fall" -v iJD=$iJD -v JD0=$JD0 \
       -v has_err=$has_err -v def_err="$def_err" -v has_lim=$has_lim \
       -v is_diff=$is_diff -v is_flux=$is_flux -v is_phase=$is_phase \
       -v err_max=$err_max -v Fcol="$Fcol" -v Ycol="$Ycol" -v Xcol="$Xcol" \
       -v perm="$perm" -v S1=$S1 -v IDcol="$IDcol" -f $awk_file \
| tee /tmp/lc-mag \
| $gfilter:q \
| graph -T $Vgraph -C $opt --pen-colors "$graph_color" \
  $plotarg -X $X:q -Y $Y:q $plotx $ploty $argv:q
echo2 "#===graph: has_err=$has_err; is_diff=$is_diff; Fcol=$Fcol; JD0=$JD0"
echo2 "#   graph_color=$graph_color"
echo2 "#...       | $IDcom '$IDarg:q' | $gfilter:q "
exit 0
