#!/bin/bash
	
if [ $# -lt 1 ]; then echo "USAGE: $0 <fits_file>"; exit; else fits=$1; fi

fits=$1                
if ! [ -s $fits ]; then echo "Check the fits file"; exit; fi
imhead_path=$(which imhead);
if [ -z $imhead_path ]; then echo "Imhead not found! Abborting."; fi

#naxis=$(imhead $fits | grep -iw naxis | sed s/NAXIS// | tr -d [:alpha:] | tr -d [:punct:] | tr -d [:blank:])
#naxis1=$(imhead $fits | grep -iw naxis1 | sed s/NAXIS1// | tr -d [:alpha:] | tr -d [:punct:] | tr -d [:blank:])
naxis=$(imhead $fits | grep -iw naxis | sed s/NAXIS// | awk '{printf "%d\n", $2}' )
naxis1=$(imhead $fits | grep -iw naxis1 | sed s/NAXIS1// | awk '{printf "%d\n", $2}' )
naxis2="";
if [ $naxis -ne 1 ]; then naxis2=$(imhead $fits | grep -iw naxis2 | sed s/NAXIS2//  | awk '{printf "%d\n", $2}' ); fi
#start=$(imhead $fits | grep -iw crval1 | sed -e s/CRVAL1// | tr -d [:alpha:] | tr -d [:punct:] | tr -d [:blank:]); 
#step=$(imhead $fits | grep -iw cdelt1 | sed -e s/CDELT1// | tr -d [:alpha:] | tr -d [:blank:] | tr -d [:punct:] | sed s/0/0./)
start=$(imhead $fits | grep -iw crval1 | sed -e s/CRVAL1// | tr -d [[=\'=]] |  awk '{if ($2<10) printf "%9.4f\n", 10^$2; else printf "%9.4f\n", $2*1.;}' )
step=$(imhead $fits | grep -iw cdelt1 | sed -e s/CDELT1// | tr -d [[=\'=]] | awk '{printf "%13.6f\n", $2*1.}' )
if [ -z "$step" ]; then step=$(imhead $fits | grep -iw cd1\_1 | sed -e s/CD1\_1// | tr -d [[=\'=]] | awk '{printf "%13.6f\n", $2*1.;}' ); fi
# If step<0.1 then we have exponential scale :
end="";
if [  $(echo 0.1/$step | bc) -gt 1 ]; then 
	lg0=$(imhead $fits | grep -iw crval1 | sed -e s/CRVAL1// | tr -d [[=\'=]] |  awk '{printf "%6.4f\n", $2;}' ) ; 
	if [ $naxis -ne 1 ]; then tot=$naxis2; else tot=$naxis1 ; fi ; 
	end=$(echo "$lg0+$step*($tot-1)" | bc -l | awk '{printf "%9.4f\n", 10^$1}'); 
	step=$(echo "scale=4; ($end - $start)/$tot" | bc -l)	; 
fi 
	
#echo $start $step $naxis $naxis1 $naxis2
if [ -z "$end" ]; then  
if [ $naxis -eq 1 ]; then end=$(echo "$start+$step*($naxis1-1)" | bc -l) ; else  
	     if [ $naxis2 -lt $naxis1 ]; then end=$(echo "$start+$step*($naxis2-1)" | bc -l); 
	     				 else end=$(echo "$start+$step*($naxis1-1)" | bc -l);
	     fi				 
fi	     	
fi
if [ $# -eq 2 ]; then 
   if [ $naxis -eq 2 ]; then if [ $naxis2 -lt $naxis1 ]; 
                             then echo "$start $end $step $naxis1"; 
	                     else echo "$start $end $step $naxis2"; 
	                     fi
   else echo "$start $end $step $naxis1";
   fi	                     
else echo  "$start $end"; 
fi
