#!/bin/bash

# eq2gal [-h]  ra dec
#              returns l,b (all in degrees)
# ref: https://www.atnf.csiro.au/people/Tobias.Westmeier/tools_coords.php

HELP=0; INVALID=0;

while getopts h optval
do 
   case $optval in
	h) HELP=1;;
	*) INVALID=1;;
    esac
done

[ $# -eq 0 ] && HELP=1;
if [ $INVALID -eq 1 ]; then exit -1; fi
if [ $HELP -eq 1 ]; then
	echo "eq2gal [-h] ra dec"
	echo "       returns l,b (all in degrees)"; exit; fi
if [ $# -ne 2 ]; then
	echo " need ra, dec but received $# parameters";exit -1; fi

ra=$1; dec=$2;

echo $ra $dec |\
awk 'BEGIN{pi=3.141592653589793; torad=pi/180;
           alpha0=192.8595;     #RA of North Galactic Pole (NGP)
           delta0 = 27.1284;    #Dec of NGP
           l0 = 122.9320;       #Galactic longitude of NGP

           c2=cos(delta0*torad); s2=sin(delta0*torad)}
       {ra =$1; dec=$2; 
        delta=dec*torad;
	c1=cos((ra-alpha0)*torad); s1=sin((ra-alpha0)*torad);
	A = cos(delta)*s1
	B = sin(delta)*c2-cos(delta)*s2*c1;
	lp = atan2(A,B)/torad;
	l = l0-lp;
	sinb=sin(delta)*s2+cos(delta)*c2*c1;
	b = atan2(sinb,sqrt(1-sinb^2))/torad;
	printf "%0.6f \t %0.6f\n", l, b}' 
