#!/bin/bash
# set -x

js9 -a --width 1100 --height 770 &
XPID=$!
printf "waiting for js9 window "
while [ x"`js9 targets`" != x1 ]; do
  printf "."
  sleep 1
done
printf " OK\n"

# Chandra event file of Kes75 SNR
file="data/kes75/kes75_evt2.fits.gz"

# Chandra energy filters
filter[1]="energy=500:1500"
filter[2]="energy=1500:2500"
filter[3]="energy=2500:8000"

# colormaps
cmap[1]="red"
cmap[2]="green"
cmap[3]="blue"

# load x-ray binary table
echo "loading Chandra event file: $file"
js9load $file '{"scale":"log"}'

# test upload
js9 UploadFITSFile

sleep 5

# turn blending off (since default is on)
js9 BlendImage false

# process each of the event filters
for i in {1..3}; do
  # process new filter
  echo "processing filter: ${filter[$i]}"
  # generate image section using event filter into a separately displayed image
  js9 DisplaySection '{"filter":"'${filter[$i]}'","separate":true}'
  # it actually takes a bit of time
  sleep 2
  j=`expr $i + 1`
  # the new file with have a <n> string appended to its id
  id="kes75_evt2.fits.gz[EVENTS]<$j>"
  # set image scale and assign one of the RGB colormaps
  js9 SetScale "log"            '{"display":"'$id'"}'
  js9 SetColormap "${cmap[$i]}" '{"display":"'$id'"}'
done

# blend all the images
echo "blend all images"
js9 BlendDisplay true

echo "resize display"
js9 ResizeDisplay 256

echo "separate display"
js9 SeparateDisplay

sleep 2

echo "add region"
js9 AddRegions 'ICRS;circle(18:46:24.95,-02:58:29.552,7.38")'

sleep 2

echo "sync images (colormap, regions)"
js9 SyncImages '["colormap", "regions"]'

echo "set colormap to viridis in first image"
js9 SetColormap viridis 4.4 0.078

sleep 2

echo "change region position in first image"
js9 ChangeRegions all '{"deltax":62,"deltay":20}'

sleep 5

# echo -n "press <cr> when done ... "
# read answer
echo killing $XPID ...
pkill -TERM -P $XPID
