#!/bin/tcsh -ef
if ("$1" == "") then
    echo "error: no table name specified"
    exit 1
endif
if ("$jdb" == "") then
    echo "env var jdb not set.  should be something like jackson20060125"
    exit 1
endif
set table = "$1"
set outpath = "/san/sanvol1/visiGene/offline/jax/$jdb"

set sql = "select c.name, t.name, c.length from syscolumns c, sysobjects o, systypes t where o.id=c.id and o.type='U' and t.usertype=c.usertype and o.name='"$table"'order by o.name, colid"


query "$sql" "bcp" > tempfields

sed -i -e 's/|/\t/g' tempfields

#cat tempfields
set fields = ( `cat tempfields` )

# make create-sql
echo "" > tempsqldef
echo "DROP TABLE IF EXISTS $table;" >> tempsqldef
echo "CREATE TABLE $table ("  >> tempsqldef

set sep = " "
while ("$fields" != "")
    set field = $fields[1] 
    shift fields
    set type = $fields[1] 
    shift fields
    set length = $fields[1] 
    shift fields
    #echo $field $type $length
    if ( ("$type" == "char") || ("$type" == "varchar") || ("$type" == "int") || ("$type" == "bit")) then
	if ("$type" == "bit") then
	    set type = "tinyint"   #workaround for mysql5.0
	endif
	echo "$sep$field $type($length)" >> tempsqldef
    else	    
	echo "$sep$field $type" >> tempsqldef
    endif	    
    set sep = ","
end

echo "); " >> tempsqldef

cat tempsqldef
cp tempsqldef ${outpath}/${table}.sql

if ( ! -d /scratch/visiGene/temp ) then
    mkdir -p /scratch/visiGene/temp
endif    

#fetch rows of table using bcp
set cmd = "freebcp $table out /scratch/visiGene/temp/temp.bcp -S gondor.informatics.jax.org:4025 -U kent -PJKent01 -c -t <UCSCtabUCSC> -r <UCSCnewlineUCSC>"
echo $cmd
$cmd

mysqlEscape -tabSep < /scratch/visiGene/temp/temp.bcp > ${outpath}/${table}.tab

if ( -e /scratch/visiGene/temp/temp.bcp ) then
    rm /scratch/visiGene/temp/temp.bcp	
endif    


