#!/bin/sh
# @(#)FIX.NA version 3.8 created 2/12/96
# @(#)Copyright (c), 1987, 1996 StatSci, Inc.  All rights reserved.

tmpdir=${TMPDIR:-/tmp}

. $SHOME/adm/cmd/DIRNAMES

case $# in
	0) dir=${DATA_DIR} ;;
	1) dir=$1 ;;
	*) echo "Syntax: Splus FIX.NA [data_directory]" >&2
	   echo "Default for 'data_directory' is ${DATA_DIR}" >&2
	   exit 1
	   ;;
esac

if test ! -d $dir; then echo "no directory $dir" >&2 ; exit 1; fi

if test -d $dir.bak; then echo "$dir.bak exists. Move it first." >&2 ; exit 1; fi

mv $dir $dir.bak
if test ! -d $dir.bak; then echo "couldn't mv $dir $dir.bak" >&2 ; exit 1; fi

mkdir $dir 

unset S_FIRST
tmp=$tmpdir/na.$$
S_WORK=$tmp.SWORK
export S_WORK
mkdir $S_WORK


Splus <<!
	# wrap whole thing in {} so the entire expression will abort
	# if there are any dumpable errors.
	{
	n <- length(search())
	old <- n + 1
	new <- n + 2
	attach("$dir.bak", pos=old)
	attach("$dir", pos=new)
	if ((search()[new] != "$dir") || (search()[old] != "$dir.bak"))
		stop("attach failed")
	obj.names <- objects(where=old)
	obj.exists <- vector("logical", length(obj.names))
	for (i in seq(along=obj.names))
		obj.exists[i] <- exists(obj.names[i], where=old)
	obj.names <- obj.names[obj.exists]
	for (i in obj.names)
		assign(i, fix.NA(get(i, where=old)), where=new)
	cat("", file="$tmp.fixok")
	}
!

if test ! -r $tmp.fixok
then
	echo "Errors in converting $dir. Originals are in $dir.bak" >&2
	exit 1
fi
	
if test -r $dir.bak/${AUDIT_FILE} 
then
	rm -f $dir/${AUDIT_FILE}
	cp $dir.bak/${AUDIT_FILE} $dir
fi

echo "Objects in $dir converted. Originals are in $dir.bak" >&2

ls -a $dir.bak | sed -e '/^\.$/d' -e '/^\.\.$/d' -e '/^\.Audit$/d' | 
	sort > $tmp.bk.dir
ls -a $dir |     sed -e '/^\.$/d' -e '/^\.\.$/d' -e '/^\.Audit$/d' | 
	sort > $tmp.dir
comm -23 $tmp.bk.dir $tmp.dir > $tmp.comm
if test -s $tmp.comm
then
	echo >&2 "	Warning: These files are no longer in $dir
	You may wish to get them from $dir.bak:
"
	cat $tmp.comm >&2
fi

rm -rf $tmp.*
