#!/usr/bin/ksh 
#
# Usage:
#         processing_stream datadir
#
# outputs:
#         SPM_PROC_TYPE
#         E-mail address
#         Reference number
#         Reference function file name
#
# The input datadir is scanned for the first *.info file that references
# a non-zero paradigm number.  That number, if found, is used to select
# the reference function.  The reference function is searched to report
# the SPM_PROC_TYPE and the E-mail address.
#
# If not found, the outputs are set to:
#         0
#         nobody
#         0
#         NoRefFunction
#  
# In the reference function, the search variables are referred to as:
#         processing_type
#         email
#
. $WFU_PATH/global.site.ksh
datadir=$1
table=$refdir/paradigm_lookup_table
#
# find the first non-zero paradigm number
#
#refnum=`grep -h fMRIParadigmNumber $datadir/*.info | cut -f2,2`
refnum=0
x=`grep -h fMRIParadigmNumber $datadir/*.info | cut -f2,2`
for num in $x
    do
        tempnum=$num
        enotation=`echo $tempnum | grep e`
        if (test ${#enotation} -gt 0) then
            value=`echo $tempnum | cut -d 'e' -f1,1`
            let ndec=`echo $tempnum | cut -d 'e' -f2,2`
            let ntotal=1
            let n=ndec
            while (test n -gt 0)
                do
                    let ntotal=$ntotal*10
                    let n=$n-1
            done
            tempnum=`echo $value $ntotal | awk '{ print $1*$2 }'`
        fi
        if (test $tempnum != "0") then
            refnum=$tempnum
            break;
        fi
    done
#
# find the reference function associated with the reference number
#
ref=''
if (test $refnum != "0") then
    ynum=`grep -h $refnum $table | grep -v ';' | awk '{print $1}'`
    set -A ynam `grep -h $refnum $table | grep -v ';' | awk '{print $2}'`
    let lineno=0
    for num in $ynum
        do
            #if (test $num -eq $refnum) then
            if (test $num = $refnum) then
                ref=${ynam[lineno]}
                break;
            fi
            let lineno=lineno+1
    done
fi
#
# search the reference function for the processing type and e-mail address
#
proc_type=0
email=nobody
if (test ${#ref} -gt 0) then
    x=`grep -h ':' $ref | grep -v ';' | grep processing_type`
    if (test ${#x} -gt 0) then 
        #echo $x
        proc_type=`echo $x | cut -d':' -f2,2 | cut -d';' -f1,1`
    fi
    x=`grep -h ':' $ref | grep -v ';' | grep email`
    if (test ${#x} -gt 0) then 
        #echo $x
        email=`echo $x | cut -d':' -f2,2 | cut -d';' -f1,1`
    fi
else
    ref="NoRefFunction"
fi
#
# report the results
#
echo $proc_type $email $refnum $ref
