#!/bin/csh
#
# ftp_ogle -- ftp download OGLE files
#
# 2006 Mar Keith Horne @ St.Andrews
# 2009 Jul KDH @ StA - ftp -> sftp
#
set year = $1
set first = $2
set last = $3
set what = $4

echo "#######################################"
date

# year

if( $year == "" ) then
	echo -n "Year (e.g. 2006) : "
	set year = $<
endif

if( $year < 1980 ) then
	echo ERROR $year invalid
	exit
endif


# first and last event

if( $first == "" ) then
	echo -n "First event : "
	set first = $<
endif
if( $last == "" ) then
	echo -n "Last event  : "
	set last = $<
endif
if( $last < $first ) then
	echo ERROR $first exceeds $last
	exit
endif
@ n = ( $last - $first ) + 1
echo Events $first thru $last total $n

# what to download

if( $what == "" ) then
	echo "Download p(hot), t(ar), or b(oth) ?"
	echo -n "What to download : "
	set what = $<
endif

if( $what == "p" ) then
	echo "Download only phot files."
set f = ftp_ogle_$year"_"$first"_"$last"_phot"
else
if( $what == "t" ) then
	echo "Download only tar files."
set f = ftp_ogle_$year"_"$first"_"$last"_tar"
else
if( $what == "b" ) then
	echo "Download both phot and tar files."
set f = ftp_ogle_$year"_"$first"_"$last"_both"
else
	echo "ERROR Unsure what you want to download."
	exit
endif
endif
endif

sleep 1s

# ftp command file

echo ftp command file : $f
if( -e $f ) then
	\mv $f $f~
endif
touch $f

# ftp commands

echo "open ftp.astrouw.edu.pl" >> $f
echo "user anonymous kdh1@st-and.ac.uk" >> $f
echo "bin" >> $f
echo "hash" >> $f
echo cd ogle/ogle3/ews/$year >> $f
@ k = $first
#echo k $k
while ( $k <= $last )
	set n = 00$k
#	echo n $n
	if( $k >= 10 ) set n = 0$k
	if( $k >= 100 ) set n = $k
	set event = OB-$year-$n
	echo $k $n $event
	if( $what == "b" || $what == "t" ) then
		echo "get blg-$n.tar.gz" >> $f
	endif
	if( $what == "b" || $what == "p" ) then
		echo "get blg-$n/phot.dat $event.dat" >> $f
	endif
@ k ++
end
echo "quit" >> $f

# support free abortions
echo
echo ftp commands in : $f
cat $f
	echo -n "ABORT now or <CR> to proceed : "
	set finish = $<

# do the deed
echo Starting OGLE data download.
date
cat $f | sftp -i -n
echo OGLE data download complete.

date
echo "#######################################"
