#!/bin/csh -f
#
# 12/18/89  James  Created.
# 04/11/90  James  Added -ok and make -tmp safe.
# 05/02/90  James  Added trail file vers check (275), -tmp fix.
# 06/07/90  James  Run pro in the tmp directory, allow y/n.
# 06/25/90  James  Prompt for list of files to cnvt was confusing.
# 08/09/90  James  quote . in greps, core file in convdir too, added dg,
#                  ibm_rs6000,olivetti860.
# 08/27/90  James  Added .mfg
# 09/17/90  6.0 James  Version, user's config.pro,  prjutil to 
#                      bypass prj header.  Action and Warn if {dms,nlo}
#                      servers are sensed '-servs' can override. 
#                      Set SGI gfxnum=0 for 5.0-9011 and above;
#                      prompt_on_exit, ignore_family_type, -prjdir,
#                      which procmd, * in prj create, '-ftab', removed 
#                      objrefdir to fix .mfg.  cd fix. -run, prjdir 
#                      fixes: vers when target=start, DO convert
#                      non-proproj. wc_maxdirlen high by def.
#                      trlchk for objects button.  better prjdir vers 
#                      fix. trlchk for mode button, do drw before asm.
#                      dot.awk. whichline_tmp. -prj_name. reorder log, added 
#                      procmd. processing msg. targetdir defs to startdir 
#                      if not set in args mode. prj_name interface. check
#                      fetch status. fix -prjdir file in sub-dir ver.
#                      core in tmpdir.
# 11/05/90  6.1 James  Fix df output and adjust fcol for sys5 m/c's.
# 11/19/90  6.2 James  svopt_val is 'true' for 5.2
# 11/29/90  6.3 James  Fixed 'which' for ps/2, rt, tek.
# 01/03/90  6.4 James  prj_repfile for 6.1
# 01/21/90  6.5 James  mv -f, discard invalid soft links. shorten __convert__ 
#                      to __cv__, cd to initialdir before rm tmpdir.
# 01/25/90  6.6 James  prj_repfile for A-25-06+
# 02/23/90  6.7 James  sun -> sun3,sun4,sun386.
# 03/07/90  7.0 James  version change - 7.0 shipped w/ Pro/E 7.0
#                      added hp700. Fixed mcol/fcol for RT.
# 04/01/90  7.1 James  if est > avail space ask whether to continue.
# 04/17/90  7.2 James  Removed some things.
# 04/19/90  7.3 James  Obsoleted ibm_rt, olivetti860, hp800.
# 04/23/90  7.4 James  filter out change_prop.
# 05/16/90  7.5 $$1 James  better space est. fixed dot in dir path problem.
#                          for hp3/7 use bdf not df.
# 08/05/90  7.6 $$2 James  import_mode. Pro/PROJ commands for 8.0 & conv.
# 09/11/90  7.7 $$3 James  Fixed 1st pass for local prj_name conv.
# 09/18/91  8.0 $$4 James  Allowed for MISC & CHANGE DIR
# 09/19/91  8.1 $$5 James  Fix hang on bad config file. A0-4 papersizes.
#                          mult. modes, avoid 8.0 project file. -ps for 7.0
#                          only (undoc).
# 05/09/92  8.2 $$6 James  sgi_r4k. Added globbing around top2lines.
#                          m88k
# 08/20/93  8.3 $$7 James  sun4_solaris; removed old machines, added alpha_unix.
# 10/15/93  8.4 $$8 James  sun4_solaris fix.
# 12/08/93  12.0 $$9 James Added hitachi.
# 05/11/94  12.1 $$10 James Fixed nonoline for sun4_solaris, STORE->SAVE at 13.0
# 09/15/95  16.0 $$11 Harry changed gfxnum from 7 to 0 for sgi machines
# 10/10/95  16.0 $$12 Harry changed df command from "/bin/df" to "/bin/df -k" 
#			    for sun4_solaris.
# 05/10/96  17.0 16.0 $$13 Jane overwritten "trail_dir" in config.pro in home dir.
# 05/17/96  17.0 16.0 $$14 Jane added sgi_elf2.      
# 06/10/96  17.0 $$15 Harry Changed fcol from "r" to "4" for alpha_unix
# 07/14/98  20.0 $$16 ZRL Added hp8k
# 05/23/00  I-03-29     JJE Added sgi_mips4
# 04/11/01  I-03-39 $$17 TWH support trail_dir in config.sup
# 10/27/02  J-03-36 $$18 Vaza Support of "Save" for j0151 and j0336.
# 05/30/03  K-01-08 $$19 Vaza Added conf. opt. "import_in_file_open no".

set name="$0"
set name="$name:t"
set script_vers="12.1"
set pid="$$"
set arglist=( $* )
set initialdir="$cwd"

unset full_mode
unset import_mode
unset cvt8_mode
if ($?PRO_CVTMODE) then
   switch ($PRO_CVTMODE)
      case import
         set import_mode
         set name="proigsutil"
      breaksw

      case cvtprj8
         set cvt8_mode
         set name="proprjcvt"
      breaksw

      default
         echo "ERROR:  $PRO_CVTMODE - unrecognised mode."
         exit 1
      breaksw
   endsw
else
   set full_mode
endif

# UTILITY DEFNS
# prjutil allows removal and insertion of the project info header on
# objects 'submit'ted under a project - this info makes object 
# unreadable unless it is first 'fetched'.
set prjutil          = "procvtutil"
set prjutil_usage    = "3"
set prjutil_noaction = "2"
set prjutil_bad      = "1"
set prjutil_good     = "0"

# BANNER
set lm="14"
set greeting="$name v$script_vers -  the Pro/ENGINEER conversion utility"
set numscores=`echo "$greeting" | wc -c`
@ numscores--
echo ""
echo ""
repeat $lm echo -n " "; echo "$greeting"
repeat $lm echo -n " "; repeat $numscores echo -n "-"
echo ""
echo ""

# CHECK THE MACHINE TYPE AND UTILITIES

set mc_type=""
if ($?PRO_MACHINE_TYPE != 0 ) then
   set mc_type=$PRO_MACHINE_TYPE
endif
goto MACHINE_CONFIG
MACHINE_CONFIG_DONE:

if (! $?import_mode) then
unset prjutil_exists
if ($?use_which) then
   set which_ret=`which $prjutil`
   set whichline=`echo "$whichline_tmp" | sed s/__CMD__/$prjutil/`
   if (`echo "$which_ret" | egrep "$whichline" | wc -l` == 0) set prjutil_exists
else
   $prjutil >& /dev/null
   if ($status == $prjutil_usage) set prjutil_exists
endif
if (! $?prjutil_exists) then
   echo ""
   repeat $lm echo -n " "; echo "WARNING:  $name utility file '$prjutil' not accessable."
   repeat $lm echo -n " "; echo "Please check installation of $name."
   repeat $lm echo -n " "; echo "If you continue, any files submitted under projects"
   repeat $lm echo -n " "; echo "will not be converted."
   if ($#arglist < 1) then
      echo ""
      repeat $lm echo -n " "; echo -n "Do you really want to continue (y/n) [y] ?: "
      set ans="$<"
      echo ""
      if ("$ans" =~ n* || "$ans" =~ N*) exit 1
   endif
endif
endif


# Variables usefull for both input modes
set size_choice=" A B C D E F A0 A1 A2 A3 A4 "

if ($#arglist < 1) then           ### CONVERSATIONAL INPUT MODE ###

set unsetdir_val="/dev/null/undefined"

echo ""
echo "   Interactive mode - you will be prompted for answers, hit <RETURN>"
echo "   to get default values in []'s when available."
echo ""
echo "   Use '$name -help' for more information, including command-line arguments."
echo ""
echo ""
set bad_procmd
while ($?bad_procmd)
   echo -n "Name of command to run Pro/ENGINEER ?: "
   set procmd="$<" 
   if ("$procmd" == "") continue

   set raw_procmd="$procmd"
   if ($?use_which) then
      set procmd=`which $procmd |& tail -1`
      if (-x "$procmd") unset bad_procmd
   else
      set procmd="/bin/$procmd"
      if (-x "$procmd") unset bad_procmd
   endif
   if ($?bad_procmd) then
      echo ""
      echo "ERROR:  '$raw_procmd' - no such command"
      echo ""
   endif
end
echo ""

# set proe_lp to point to the install directory
# used later to check config.sup

set fullprocmdname=`ls -l $procmd | awk '{print $NF}'`
set t_procmdname="$fullprocmdname:t"
set h_procmdname="$fullprocmdname:h"
set proe_lp
if ($h_procmdname == $t_procmdname) then
  set proe_lp="$cwd:h"
else
  pushd $h_procmdname
  set proe_lp="$cwd:h"
  popd
endif
unset h_procmdname
unset t_procmdname
unset fullprocmdname

set def="drw"
set impfmt=""
set choice=" drw prt "
while ($?import_mode && `echo "$choice" | grep " $impfmt " | wc -l` == 0)
   echo "Convert to parts or drawings (choice: $choice)"
   echo -n "[$def] ?: "
   set impfmt="$<"
   set impfmt=`echo "$impfmt" | tr \[A-Z\] \[a-z\] | tr -d ' '`
   if ("$impfmt" == "") set impfmt="$def"
   echo ""
end

# Next undocumented variable is only avail in param mode - for 7.0 only.
set papersize=""

set def="igs"
set impext=""
while ($?import_mode &&"$impext" == "")
   echo "Import file extension"
   echo -n "[$def] ?: " 
   set impext="$<"
   set impext=`echo "$impext" | tr \[A-Z\] \[a-z\] | tr -d ' '`
   if ("$impext" == "") set impext="$def"
   echo ""
end

set def="no"
set prjreply=""
if ($?cvt8_mode) set prjreply="yes"
set choice=" yes no "
while (`echo "$choice" | grep " $prjreply " | wc -l` == 0 && ! $?import_mode)
   echo "Do you wish to convert a project to Release 8.0 (choice: $choice)"
   echo -n "[$def] ?: "
   set prjreply="$<"
   set prjreply=`echo "$prjreply" | tr \[A-Z\] \[a-z\] | tr -d ' '`
   if ("$prjreply" == "") set prjreply="$def"
   if ("$prjreply" =~ y*) set prjreply="yes"
   if ("$prjreply" =~ n*) set prjreply="no"
   echo ""
end
set prj_conv=""
if ("$prjreply" == "yes") then
   unset valid_prjconv
   while (! $?valid_prjconv)
      echo "What is the project name"
      echo -n "?: "
      set prj_conv="$<"
      set prj_conv=`echo "$prj_conv" | tr \[A-Z\] \[a-z\] | tr -d ' '`
      set valid_prjconv
      echo ""
   end
endif

set def="no"
set prjreply=""
set choice=" yes no "
while (`echo "$choice" | grep " $prjreply " | wc -l` == 0 && ! $?import_mode && "$prj_conv" == "")
   echo "Do you wish to convert Pro/PROJECT files (choice: $choice)"
   echo -n "[$def] ?: "
   set prjreply="$<"
   set prjreply=`echo "$prjreply" | tr \[A-Z\] \[a-z\] | tr -d ' '`
   if ("$prjreply" == "") set prjreply="$def"
   if ("$prjreply" =~ y*) set prjreply="yes"
   if ("$prjreply" =~ n*) set prjreply="no"
   echo ""
end

if ("$prjreply" == "yes") then
   set prjver=""
   set def="5.0"
   set choice=" 5.0 6.0+ "
   while (`echo "$choice" | grep " $prjver " | wc -l` == 0)
      echo "Converting FROM what version of Pro/ENGINEER (choice: $choice)"
      echo -n "[$def] ?: "
      set prjver="$<"
      set prjver=`echo "$prjver" | tr \[A-Z\] \[a-z\] | tr -d ' '`
      if ("$prjver" == "") set prjver="$def"
      if ("$prjver" == "5") set prjver="5.0"
      if ("$prjver" == "6") set prjver="6.0+"
      echo ""
   end

   if ("$prjver" == "5.0") then
      set prjdir="yes"
      set prj_name=""
   else
      set prjdir="no"
      set prj_name=""
      unset valid_prjname
      while (! $?valid_prjname)
         echo "What is the project name"
         echo -n "?: "
         set prj_name="$<"
         set prj_name=`echo "$prj_name" | tr \[A-Z\] \[a-z\] | tr -d ' '`
         set valid_prjname
         echo ""
      end
   endif
else if ("$prjreply" == "no") then
   set prj_name=""
   set prjdir="no"
else 
   set prj_name=""
   set prjdir=""
endif

set def="$cwd"
set startdir="$unsetdir_val"
while (! -d $startdir && "$prj_name" == "" && "$prj_conv" == "") 
   echo "Name of directory containing files to convert"
   echo -n "[$def] ?: "
   set startdir="$<"
   if ("$startdir" == "") set startdir="$def"
   if (! -d $startdir) then
      echo "ERROR:  directory does not exist - '$startdir'"
   endif
end
if ("$startdir" != "$unsetdir_val") then
   set startdir=`(cd $startdir; echo $cwd)`
   echo ""
else
   set startdir=""
endif

set list=""
unset valid_list
while (! $?valid_list && "$prj_name" == "" && "$prj_conv" == "")
   echo "Name of file containing list of files to convert"
   echo -n "hit <RETURN> to convert all files ?: "
   set list="$<"
   if ("$list" == "") then
      set valid_list
   else if (! -e "$list") then
      echo "ERROR:  file does not exist - '$list'"
      continue
   endif
   set valid_list
   echo ""
end

set descend=""
if ("$list" == "" && "$prj_name" == "" && "$prj_conv" == "") then
   set def="no"
   set choice=" yes no "
   unset valid_ans
   while (`echo "$choice" | grep " $descend " | wc -l` == 0)
      echo "Recursively convert files in dirs encountered (choice: $choice)"
      echo -n "[$def] ?: "
      set descend="$<"
      set descend=`echo "$descend" | tr \[A-Z\] \[a-z\] | tr -d ' '`
      if ("$descend" == "") set descend="$def"
      if ("$descend" =~ y*) set descend="yes"
      if ("$descend" =~ n*) set descend="no"
   end
   echo ""
endif

set def="$startdir"
set targetdir="$unsetdir_val"
while (! -d $targetdir && "$prj_name" == "" && "$prj_conv" == "")
   echo "Name of directory in which to put converted files"
   echo -n "[$def] ?: "
   set targetdir="$<"
   if ("$targetdir" == "") set targetdir="$def"
   if (! -d "$targetdir") echo "ERROR:  '$targetdir' does not exist"
end
if ("$targetdir" != "$unsetdir_val") then
   set targetdir=`(cd $targetdir; echo $cwd)`
   echo ""
else
   set targetdir=""
endif

set geommode=""
set def="nogeom"
if ($?import_mode && "$impfmt" == "drw") set geommode="$def"
set choice=" geom nogeom "
while (`echo "$choice" | grep " $geommode " | wc -l` == 0 && "$prj_conv" == "")
   echo "Geometry mode (choice: $choice)"
   echo -n "[$def] ?: "
   set geommode="$<"
   if ("$geommode" == "") set geommode="$def"
   echo ""
end

# Fixed
set storemode="long"
if ("$prj_conv" != "") set storemode=""

set def="no"
set purgefiles=""
set choice=" yes no "
while (`echo "$choice" | grep " $purgefiles " | wc -l` == 0 && "$prj_name" == "" && ! $?import_mode && "$prj_conv" == "")
   echo "Purge each file after conversion (choice: $choice)"
   echo -n "[$def] ?: "
   set purgefiles="$<"
   set purgefiles=`echo "$purgefiles" | tr \[A-Z\] \[a-z\] | tr -d ' '`
   if ("$purgefiles" == "") set purgefiles="$def"
   if ("$purgefiles" =~ y*) set purgefiles="yes"
   if ("$purgefiles" =~ n*) set purgefiles="no"
   echo ""
end

set def="no"
set forceconvert=""
set choice=" yes no "
while (`echo "$choice" | grep " $forceconvert " | wc -l` == 0 && ! $?import_mode && "$prj_conv" == "")
   echo "Force conversion of all files (choice: $choice)"
   echo -n "[$def] ?: "
   set forceconvert="$<"
   set forceconvert=`echo "$forceconvert" | tr \[A-Z\] \[a-z\] | tr -d ' '`
   if ("$forceconvert" == "") set forceconvert="$def"
   if ("$forceconvert" =~ y*) set forceconvert="yes"
   if ("$forceconvert" =~ n*) set forceconvert="no"
   echo ""
end

set killdelay=""
set def="0"
if ("$prj_conv" != "") set killdelay="$def"
while ("$killdelay" == "")
   echo "Maximum time for any file conversion (choice: 	number of mins, 0 = unlimited)"
   echo -n "[$def] ?: "
   set killdelay="$<"
   if ("$killdelay" == "") set killdelay="$def"
   echo ""
end

set def="/tmp"
set tmpdir="$unsetdir_val"
while (! -d $tmpdir)
   echo "Temporary work directory" 
   echo -n "[$def] ?: "
   set tmpdir="$<"
   if ("$tmpdir" == "") set tmpdir="$def"
   set tmpdir=`(cd $tmpdir; echo $cwd)`
   if (! -d "$tmpdir") echo "ERROR:  '$tmpdir' does not exist"
   echo ""
end

set min_space=""
set def="0"
if ("$prj_conv" != "") set min_space="$def"
while ("$min_space" == "" && "$prj_conv" == "")
   echo "Minimum disk space for any conversion (choice:  size in Kb, 0 = unlimited)"
   echo -n "[$def] ?: "
   set min_space="$<"
   if ("$min_space" == "") set min_space="$def"
   echo ""
end

set backup_ok=""

set user_cfgfile=""
if ("$prj_conv" == "") then
   set def="existing"
   ASK_CFG_NAME:
      echo "Name of a config. file to use (choice:  none, existing OR a filename)"
      echo -n "[$def] ?: "
      set user_cfgfile="$<"
      if ("$user_cfgfile" == "") set user_cfgfile="$def"
      if ("$user_cfgfile" == "none" || "$user_cfgfile" == "existing") goto CFG_NAME_DONE
      if (-e "$user_cfgfile") goto CFG_NAME_DONE
      echo "ERROR:  file does not exist - '$user_cfgfile'"
      goto ASK_CFG_NAME
   CFG_NAME_DONE:
   echo ""
endif

# Don't ask about following - intended for in-house args mode only
set validservs="all"
set ftab="no"
set runmode="-1"

else                              ### NON-CONVERSATIONAL INPUT MODE ###

#
#                       VALIDATE PARAMETERS
#

# MUST HAVE P1
set procmd="$arglist[1]"         # P1 no default
if ("$procmd" == "" || "$procmd" =~ -*) goto USAGE

set bad_procmd
if ($?use_which) then
   set procmd=`which $procmd |& tail -1`
   if (-x "$procmd") unset bad_procmd
else
   set procmd="/bin/$procmd"
   if (-x "$procmd") unset bad_procmd
endif
if ($?bad_procmd) then
   echo ""
   repeat $lm echo -n " "; echo "ERROR:  '$procmd' no such command"
   exit 1
endif

# set proe_lp to point to the install directory
# used later to check config.sup

set fullprocmdname=`ls -l $procmd | awk '{print $NF}'`
set t_procmdname="$fullprocmdname:t"
set h_procmdname="$fullprocmdname:h"
set proe_lp
if ($h_procmdname == $t_procmdname) then
  set proe_lp="$cwd:h"
else
  pushd $h_procmdname
  set proe_lp="$cwd:h"
  popd
endif
unset h_procmdname
unset t_procmdname
unset fullprocmdname

# ESTABLISH PRE-PARAMETER DEFAULTS 
if ($?import_mode) then
#  impfmt - must be set by parameter
#  papersize - undocumented only needed for 7.0, provided for emergency only
   set impext="igs"
   set purgefiles=""
   set forceconvert=""
   set prjdir=""
else
   set impext=""
   set purgefiles="___UNDEFINED___"
   set forceconvert="no"
   set prjdir="no"
endif
set impfmt=""
set papersize=""
set list=""
set startdir="___UNDEFINED___"
set targetdir="___UNDEFINED___"
set geommode="nogeom"
set storemode="long"
set descend="___UNDEFINED___"
set killdelay=0
set backup_ok=""
set tmpdir="/tmp"
set min_space=0
set user_cfgfile="existing"
set validservs="all"         # undocumented switch
set ftab="no"                # undocumented switch
set runmode="-1"             # undocumented switch
set prj_name=""
set prj_conv=""


# OVERRIDE DEFAULTS WITH PARAMETERS

set argnum="$#arglist"

unset missingpar
set i="2"
while ($i <= $argnum && ! $?missingpar)
   set curpar="$arglist[$i]"
   switch ($curpar)
      case -help
         goto USAGE
      breaksw

      case -if
         if (! $?import_mode) goto BAD_PARAM
         @ i++
         if ($i > $argnum) then
         set missingpar
         else
            set impfmt="$arglist[$i]" 
         endif
      breaksw

      case -ps
         if (! $?import_mode) goto BAD_PARAM
         @ i++
         if ($i > $argnum) then
         set missingpar
         else
            set papersize=`echo "$arglist[$i]" | tr '[a-z]' '[A-Z]'`
         endif
      breaksw

      case -ie
         if (! $?import_mode) goto BAD_PARAM
         @ i++
         if ($i > $argnum) then
         set missingpar
         else
            set impext="$arglist[$i]" 
         endif
      breaksw

      case -s
         @ i++
         if ($i > $argnum) then
         set missingpar
         else
            set startdir="$arglist[$i]" 
         endif
      breaksw

      case -l
         @ i++
         if ($i > $argnum) then
         set missingpar
         else
            set list="$arglist[$i]" 
         endif
      breaksw

      case -t
         @ i++
         if ($i > $argnum) then
	    set missingpar
         else
            set targetdir="$arglist[$i]"
         endif
      breaksw

      case -geom
         set geommode="geom"
      breaksw

      case -p
         if ($?import_mode) goto BAD_PARAM
         set purgefiles="yes"
      breaksw

      case -r
         set descend="yes"
      breaksw

      case -f
         if ($?import_mode) goto BAD_PARAM
         set forceconvert="yes"
      breaksw

      case -k
         @ i++
         if ($i > $argnum) then
	    set missingpar
         else
            set killdelay="$arglist[$i]"
         endif
      breaksw

      case -tmp
         @ i++
         if ($i > $argnum) then
	    set missingpar
         else
            set tmpdir="$arglist[$i]"
         endif
      breaksw

      case -ms
         @ i++
         if ($i > $argnum) then
	    set missingpar
         else
            set min_space="$arglist[$i]"
         endif
      breaksw

      case -ok
         set backup_ok="yes"
      breaksw

      case -c
         @ i++
         if ($i > $argnum) then
	    set missingpar
         else
            set user_cfgfile="$arglist[$i]"
         endif
      breaksw

      case -prjdir
         if ($?import_mode) goto BAD_PARAM
         set prjdir="yes"
      breaksw

      case -servs
         @ i++
         if ($i > $argnum) then
         set missingpar
         else
            set validservs="$arglist[$i]"    # undocumented switch
         endif
      breaksw

      case -ftab
         set ftab="yes"
      breaksw

      case -run
         @ i++
         if ($i > $argnum) then
         set missingpar
         else
            set runmode="$arglist[$i]"    # undocumented switch
         endif
      breaksw

      case -prj_name
         if ($?import_mode) goto BAD_PARAM
         @ i++
         if ($i > $argnum) then
         set missingpar
         else
            set prj_name="$arglist[$i]"    # undocumented switch
         endif
      breaksw

      case -prj_conv
         if ($?import_mode) goto BAD_PARAM
         @ i++
         if ($i > $argnum) then
         set missingpar
         else
            set prj_conv="$arglist[$i]"    # undocumented switch
         endif
      breaksw

      default
         BAD_PARAM:
         echo ""
         echo "ERROR:  illegal parameter: '$curpar'"
         echo ""
         goto USAGE
      breaksw
   endsw

   @ i ++
end

if ($?missingpar) then
   echo "ERROR:  must supply a string after -s,-l,-t,-k, -tmp, -c or -prj_name"
   exit 1
endif

# ESTABLISH POST-PARAMETER DEFAULTS
if ("$prj_name" == "" && "$prj_conv" == "") then
   if ("$startdir"    == "___UNDEFINED___") set startdir="$cwd"
   if ("$targetdir"   == "___UNDEFINED___") set targetdir="$startdir"
   if ("$purgefiles"  == "___UNDEFINED___") set purgefiles="no"
   if ("$descend"     == "___UNDEFINED___") set descend="no"
else
   set startdir=""
   set targetdir=""
   set purgefiles=""
   set descend=""
   if ("$prj_conv" != "") then
      set geommode=""
      set storemode=""
      set forceconvert=""
      set user_cfgfile=""
      set prjdir=""
   endif
endif
if ($?import_mode) then
   if ("$impfmt" == "") then
      echo "ERROR:  you must specify the import format using -if."
      exit 1
   endif
   if ("$impfmt" == "prt") set papersize=""
endif
if ($?cvt8_mode) then
   if ("$prj_conv" == "") then
      echo "ERROR:  you must specify the project to convert using -prj_conv."
      exit 1
   endif
endif

endif                             ### INPUT MODE ###

# MAKE SURE USER IS WARNED ABOUT BACKUPS
set def="no"
set choice=" yes no "
while (`echo "$choice" | grep " $backup_ok " | wc -l` == 0)
   echo "Satisfied with the backup of the files to be converted (choice: $choice)"
   echo -n "[$def] ?: "
   set backup_ok="$<"
   set backup_ok=`echo "$backup_ok" | tr \[A-Z\] \[a-z\] | tr -d ' '`
   if ("$backup_ok" == "") set backup_ok="$def"
   if ("$backup_ok" =~ y*) set backup_ok="yes"
   if ("$backup_ok" =~ n*) set backup_ok="no"
   echo ""
end

if ("$backup_ok" == "no") then
   echo ""
   echo "Re-run $name after backing up the files to be converted."
   echo ""
   exit 0
endif

if ($?import_mode && "$impfmt" != "drw" && "$impfmt" != "prt") then
   echo "ERROR:  -if $impfmt - valid formats are: drw or prt"
   exit 1
endif

# CHECK PARS THAT ARE FREE-FORMAT
if ("$startdir" != "") then
   if (! -d $startdir) then
      echo "ERROR:  -s; '$startdir' - no such directory exists"
      exit 1
   endif
   set startdir=`(cd $startdir; echo $cwd)`
endif

if ("$list" != "") then
   if ("$list:h" == "$list:t") set list="$initialdir/$list"
   if (! -e "$list") then
      echo "ERROR:  -l; '$list' - no such file exists"
      exit 1
   endif
endif

if ("$targetdir" != "") then
   if (! -d "$targetdir") then
      mkdir "$targetdir"
      if ($status) then
         echo "ERROR:  -t; '$targetdir' - can't create this dir"
         exit 1
      endif
   endif
   touch "$targetdir"/convert.$pid
   if ($status) then
       echo "ERROR:  -t; '$targetdir' - can't write into this dir"
       exit 1
   endif
   rm -f $targetdir/convert.$pid
   set targetdir=`(cd $targetdir; echo $cwd)`
endif

if ("$killdelay" < 60 && "$killdelay" != 0) then
   echo ""
   echo "WARNING:  Maximum file conversion time ($killdelay mins) is less than 1 hour."
   echo "          This may be too short a time."
   echo ""
endif
set killdelay_secs=`echo "$killdelay * 60" | bc`


set tmpdir="$tmpdir/$pid"
if (! -d $tmpdir) then
   mkdir $tmpdir
   if ($status) then
      echo "ERROR:  can not create tmp work dir '$tmpdir'"
      exit 1
   endif
endif
touch $tmpdir/convert.$pid
if ($status) then
   echo "ERROR:  '$tmpdir' - can't write into this tmp work dir"
   exit 1
endif
rm -f $tmpdir/convert.$pid
set tmpdir=`(cd $tmpdir; echo $cwd)`

if ("$user_cfgfile" != "none" && "$user_cfgfile" != "existing" && "$user_cfgfile" != "") then
   if (! -e $user_cfgfile) then
      echo "ERROR:  no such file $user_cfgfile"
      echo ""
      echo "        Config file values are 'none', 'existing' OR the name of"
      echo "        a config. file, type $name -help for more info."
      exit 1
   endif
   set cfgdir=""
   if ("$user_cfgfile:h" == "$user_cfgfile:t") set cfgdir="$initialdir"
   if ("$cfgdir" == "") set cfgdir="$user_cfgfile:h"
   set cfgdir=`(cd $cfgdir; echo $cwd)`
   set user_cfgfile="$cfgdir/$user_cfgfile:t"
   endif 
endif

set choice=" all dms nlo none "
if (`echo "$choice" | grep " $validservs " | wc -l` == 0) then
   echo "ERROR:  invalid value for -validservs, choices are"
   echo "        $choices"
   exit 1
endif


#
#                  GRAPHICS/RUNMODE/SERVERS 
#

set nloserv_timeout="720"  # 12 mins
set nloserv_delay="60"
set dmsserv_delay="40"
unset nlo_env
unset dms_env
if (-e /etc/nloservers.txt || -e /etc/nloserverlist.txt) then
   if ($validservs == "all" || $validservs == "nlo") then 
      set nlo_env
      echo ""
      repeat $lm echo -n " "; echo "INFO:  Running in a Pro/NLO environment."
      repeat $lm echo -n " "; echo "Pausing $nloserv_delay secs before each conversion for licence acquisition."
   endif
endif

if (-e /etc/dmsservers.txt) then
   if ($validservs == "all" || $validservs == "dms") then 
      set dms_env
      echo ""
      repeat $lm echo -n " "; echo "INFO:  Running in a Pro/PROJECT environment."
   endif
endif


# NECC. AND SUFF. CONDITIONS FOR MODES OF OPERATION
if ("$prjdir" == "yes" && ! $?prjutil_exists) then
   echo ""
   echo "ABORTING:  No Pro/PROJECT files can be converted without the"
   echo "           $prjutil utility file"
   exit 1
endif
if (("$prj_name" != "" || "$prj_conv" != "") && ! $?dms_env) then
   echo ""
   echo "ABORTING:  /etc/dmsservers.txt is not present."
   echo "           Must run in a Pro/PROJECT environment to convert a project"
   exit 1
endif


#
#                   INITIALIZATIONS
#

# NAME OF EXECUTABLE
set execname=`tail -1 $procmd | awk '{print $1}'`
if (! -x "$execname" && "$killdelay" != 0) then
   echo ""
   echo "WARNING:  Cannot determine executable name from '$procmd'"
   echo "          Setting maximum time for file conversion to unlimited"
   echo ""
   set killdelay="0"
endif


# INITIAL DIR AND LOGFILE
set logfile="$initialdir/$name.log"
touch $logfile.$$
if ($status) then
   echo "ERROR:  can't write into this directory '$initialdir'"
   exit 1
endif
rm -f $logfile.$$
if (-e $logfile) then
   mv -f $logfile ${logfile}_old
endif


# WRITE HEADER INFO TO LOGFILE
echo "# Log file produced by the PTC $name utility v$script_vers"     > $logfile
echo "#"                                                             >> $logfile
echo "# Started:       `date`"                                       >> $logfile
echo "#"                                                             >> $logfile
echo "# Directory:     $initialdir"                                  >> $logfile
echo "#"                                                             >> $logfile
echo "# Command:       $name $arglist"                               >> $logfile
echo "#"                                                             >> $logfile
echo                            "# procmd         $procmd"           >> $logfile
if ($?import_mode) then
   echo                         "# impfmt         $impfmt"           >> $logfile
   if ("$papersize" != "") echo "# papersize      $papersize"        >> $logfile
   echo                         "# impext         $impext"           >> $logfile
endif
if ("$prjdir" != "") echo        "# prjdir         $prjdir"          >> $logfile
if ("$prj_name" != "") echo      "# prj_name       $prj_name"        >> $logfile
if ("$prj_conv" != "") echo      "# prj_conv       $prj_conv"        >> $logfile
if ("$startdir" != "") echo      "# startdir       $startdir"        >> $logfile
if ("$list" != "") echo          "# filelist       $list"            >> $logfile
if ("$descend" != "") echo       "# descend        $descend"         >> $logfile
if ("$targetdir" != "") echo     "# targetdir      $targetdir"       >> $logfile
if ("$geommode" != "") echo      "# geommode       $geommode"        >> $logfile
if ("$storemode" != "") echo     "# storemode      $storemode"       >> $logfile
if ("$purgefiles" != "") echo    "# purgefiles     $purgefiles"      >> $logfile
if ("$forceconvert" != "") echo  "# forceconvert   $forceconvert"    >> $logfile
if ("$killdelay" != "0") echo    "# killdelay      $killdelay"       >> $logfile
echo                             "# tmpdir         $tmpdir"          >> $logfile
if ("$min_space" != "0") echo    "# min_space      $min_space"       >> $logfile
if ("$user_cfgfile" != "") echo  "# user_cfgfile   $user_cfgfile"    >> $logfile
echo ""                                                              >> $logfile

# MAP FILE EXTS INTO PRO/E BUTTONS
if ("$ftab" == "yes") then
   set exts = ("prt" "asm")
   set exts_out = `echo "$exts"`
   set buttons = ("#PART" "#ASSEMBLY")
else if ($?import_mode) then
   set exts = ("$impext")
   set exts_out = ("$impfmt")
   set buttons = ("")    # not used, but set for safety.
else
   set exts = ("mfg" "drw" "asm" "prt" "sec" "lay" "prj")
   set exts_out = `echo "$exts"`
   set buttons = ("#MANUFACTURE" "#DRAWING" "#ASSEMBLY" "#PART" "#SKETCHER" "#LAYOUT" "#PROJECT")
endif
set exts_re=`echo "$exts" | tr ' ' '|'`


# INDICATES A DUMMY HEADER FILE for -projdir mode
set dumheadstr="_PROCVT_DUMMY_"

set shorttypetag="ENDSPGSHORTTERMFILE"
set longtypetag="END_OF_UGC"
set rev8prjtag="#>START"            # start of second line of 8.0 prj file.

if ("$storemode" == "short") then
   set storecmd="#SHORT TERM"
else
   set storecmd="#LONG TERM"
endif
if ("$geommode" == "geom") then
   set geomcmd="#STORE GEOMETRY"
else
   set geomcmd="#NO GEOMETRY"
endif

# ESTIMATES
set s_l="1.9"        # 1.88
set s_lg="5.5"       # 5.52
set l_s="0.7"        # 0.73
set l_sg="1.4"       # 1.42
set s_sg="2.3"       # 2.29
set l_lg="2.6"       # 2.60
set safety="0.2"     # Over-estimate by 20%

set s_l="($s_l+($safety*$s_l))"
set s_lg="($s_lg+($safety*$s_lg))"
set l_s="($l_s+($safety*$l_s))"
set l_sg="($l_sg+($safety*$l_sg))"
set s_sg="($s_sg+($safety*$s_sg))"
set l_lg="($l_lg+($safety*$l_lg))"


# VALID FILE SPECS.
set ptcfiles=""
set ptcfiles_out=""
set i=1
while ($i <= $#exts)
  set comma=","
  if ($i == 1) set comma=""
  set ptcfiles="$ptcfiles${comma}*.$exts[$i]*"
  set ptcfiles_out="$ptcfiles_out${comma}*.$exts_out[$i]*"
  @ i++
end
set noglob
set ptcfiles_sp=`echo "$ptcfiles" | tr ',' ' '`
set ptcfiles_out_sp=`echo "$ptcfiles_out" | tr ',' ' '`
unset noglob


# NAME SCRATCH FILES AND DIRECTORIES
set convlist="$tmpdir/list.txt"     # the list of converts
set mergelist="$tmpdir/merge.txt"   # used in -proj mode
set msglist="$tmpdir/msg.txt"       # used in -proj mode

# Where Pro/E will store objs on each conversion.
set dumpdir="$tmpdir/dump"
mkdir $dumpdir

# proconvert's private start and target dirs (used by -prjdir mode only)
if ("$prjdir" == "yes") then
   set prvstartdir="$tmpdir/prvs"
   set prvtargetdir="$tmpdir/prvt"
   mkdir $prvstartdir
   mkdir $prvtargetdir
endif

# proconvert's private fetch dir (used by -prj_name only)
set fetchdir="$tmpdir/fetch"
mkdir $fetchdir

#
#                       GENERATE AUXILIARY FILES
#

# TRAIL FILE FRAGMENTS
# dynamic means generated much later and many (different) times.
set trlend="$tmpdir/trlend.txt"          # Get the curr trl file banner.
set trltop="$tmpdir/trltop.txt"          # The trl file banner.
set trlprj="$tmpdir/trlprj.txt"          # Prefix (no Pro/PROJECT)
set trlpprj="$tmpdir/trlpprj.txt"        # Prefix (Pro/PROJECT)
set trlpprj_r="$tmpdir/trlpprj_r.txt"    # used by -prj_name only
set trlprjcnv="$tmpdir/trlprjcnv.txt"    # used by -prj_conv only
set trlcd="$tmpdir/trlcd.txt"            # Change dir.
set trlcdcwd="$tmpdir/trlcdcwd.txt"    	 # used to oos trail file input
set trlrstr="$tmpdir/trlrstr.txt"        # Restore obj cmds
set trldone="$tmpdir/trldone.txt"        # Needed for .sec rstr
set trlbody="$tmpdir/trlbody.txt"        # Convert cmds
set trlexit="$tmpdir/trlexit.txt"        # Exit/y cmds
set trlpprjcr="$tmpdir/trlpprjcr.txt"    # Create Pro/PROJECT prj
set trlpprjdel="$tmpdir/trlpprjdel.txt"  # Delete Pro/PROJECT prj
set dummy_proj_name="${name}_tmp"
set my_cfgfile="$tmpdir/my_config.pro"   # Mandatory config.pro settings
set realcfg="$tmpdir/realcfg.pro"        # final config.pro run w/ Pro/E
set trl_tmpname="$tmpdir/trltmpnm.txt"   # transient usage. (dynamic)

set trlpfet="$tmpdir/trlpfet.txt"        # -prj_name, fetch (dynamic)
set trlpsub="$tmpdir/trlpsub.txt"        # -prj_name, submit (dynamic)
set trlpunf="$tmpdir/trlpunf.txt"        # -prj_name, unfetch (dynamic)
set trlprep="$tmpdir/trlrep.txt"         # -prj_name, report

# Obtain the current tail file version number. 
echo \!trail file version No\. 0     > $trlend   
echo "#EXIT"                        >> $trlend
echo "y"                            >> $trlend

cd $tmpdir

# Pro/E should not crash in tmpdir, but just in case..
rm -f core
touch core
chmod 000 core

touch trail.txt.$pid                # fake out the next rm
rm -f trail.txt* >& /dev/null
set trailfile="$trlend"
set temp_cfg="$proe_lp/text/config.sup"
set trail_dir
if ( -e $temp_cfg ) then
  set trail_dir=`grep trail_dir $temp_cfg | awk '{print $NF}'`
endif
set temp_cfg="$tmpdir/config.pro"
touch $temp_cfg
if (! -e "$trail_dir" ) then
  echo "trail_dir $tmpdir" > $temp_cfg
  set trail_dir="$tmpdir"
else
  pushd $trail_dir
  set last_trail=`ls trail.txt.* |tail -1`
  popd
  echo ""
  echo "WARNING: config.sup contains a trail_dir entry."
  echo ""
endif

$procmd $runmode $gfxnum 1 $trailfile >& /dev/null

rm -f $temp_cfg

pushd $trail_dir
set this_trail=`ls -tr trail.txt.* |tail -1`
if ($?last_trail) then
  if ( $last_trail == $this_trail ) then
   echo ""
   echo "ERROR:  '$procmd' - not a command to run Pro/ENGINEER"
   echo ""
   exit 1
  endif
else if (! -e $this_trail) then
   echo ""
   echo "ERROR:  '$procmd' - not a command to run Pro/ENGINEER"
   echo ""
   exit 1
endif
set trltopline = `cat $this_trail | sed -n "1 p"`
set trlnum=`echo $trltopline[$#trltopline]`
echo "$trltopline"                   > $trltop
popd


#################### TRAIL FILE VERSION CHECKS ####################

# If we are running on SGI w/ pro >= 5.0-9011 don't have to do gfx
if ("$mc_type" =~ sgi* && "$trlnum" >= "253") set gfxnum="0"

# A-24-11 + uses new report filename, changed again at a-25-06.
if ("$trlnum" <= "362") then 
   set prj_repfile="tree*.lis.1"
else if ("$trlnum" < "383") then
   set prj_repfile="*.tmp.1"
else
   set prj_repfile="*.t_r.1"
endif

# Menu button change
set cd_cmd="#CHANGE_DIR"
if ("$trlnum" >= "464") then
   set os_cmd="#MISC"
   set cd_cmd="#CHANGE DIR"
else if ("$trlnum" >= "275") then
   set os_cmd="#MISC."
else
   set os_cmd="#OS"
endif

# 6.0 button change
set obj_button=""
if ("$trlnum" == "340") set obj_button="#OBJECTS"
if ("$trlnum" >= "341") set obj_button="#MODE"

# Pro/E's ability to cd to long dirs - 31, hedge at 28 !
set maxdirlen=""
set wc_maxdirlen="1000"
if ("$trlnum" <= "255") then
   set maxdirlen="28"                   # have to do 2 cd's after this
   @ wc_maxdirlen = ($maxdirlen + 1)    # wc 'overcounts' \n
endif

# CONFIG KEYWORDS
rm -f $my_cfgfile

# prompt_on_exit         - present at 4.0, so always put it in 
echo "prompt_on_exit no" >> $my_cfgfile

echo "import_in_file_open no" >> $my_cfgfile

# store_only_in_current  - starting at 5.1, value change at 5.2
set svopt_key="store_only_in_current"
set svopt_val="yes"
if ("$trlnum" <= "294") set svopt_val="true"   # 5.1/2beta value
if ("$trlnum" >= "341") set svopt_key="override_store_back"   # 6.0 keywd
if ("$trlnum" >= "278") echo "$svopt_key $svopt_val" >> $my_cfgfile

# ignore_family_type     - starting at 6.0
if ("$trlnum" >= "331") echo "ignore_family_type yes" >> $my_cfgfile

# Mutually exclusive and Pro/E vers dependant Pro/PROJECT methods.
if ("$trlnum" >= "342") then
   if ("$prjdir" == "yes") then
      echo ""
      echo "ERROR:  project directory mode (-prjdir) is not valid with this"
      echo "        version of Pro/ENGINEER (6.0+)."
      echo "        Use project name mode (-prj_name) instead."
      exit 1
   endif
else
   if ("$prj_name" != "") then
      echo ""
      echo "ERROR:  project name mode (-prj_name) is not valid with this"
      echo "        version of Pro/ENGINEER (5.0)." 
      echo "        Use project directory mode (-prjdir) instead."
      exit 1
   endif
endif

if ("$prj_conv" != "" && "$trlnum" < "459") then
   echo ""
   echo "ERROR:  the project conversion option (-prj_conv) is not valid with"
   echo "        this version of Pro/ENGINEER - you must use Release 8.0"
   echo ""
   exit 1
endif

# No interactivity for real Pro/PROJECT mode
if ("$prj_name" != "") then
   echo "user_proj_interface no" >> $my_cfgfile
endif

# import_mode switches - stops potential interactivity in igs drw read.
if ($?import_mode) then
   echo "iges_drawing_number 1" >> $my_cfgfile
   echo "iges_drawing_scaling translate" >> $my_cfgfile
endif

# 8.0 project button renames
if ("$trlnum" >= "457") then
   set modify_keywd="#LATEST"
   set unfetch_keywd="#UNLOCK"
else
   set modify_keywd="#MODIFY"
   set unfetch_keywd="#UNFETCH"
endif

# 8.0 drawing iges in button changes
if ("$trlnum" >= "481")  then
   set igsdrw_80
else
   unset igsdrw_80
   if ("$impfmt" == "drw" && `echo "$size_choice" | grep " $papersize " | wc -l` == 0) then
      echo ""
      echo "ERROR:  You must use the 7.0 option -ps option - currently $papersize -"
      echo "        valid sizes are: $size_choice"
      goto QUICK_EXIT
   endif
endif

# 13.0 store -> save
if ("$trlnum" >= "730")  then
   set saveit_cmd="#SAVE"
else
   set saveit_cmd="#STORE"
endif

####################################################################

# reserved config options
set tabookeys=`cat $my_cfgfile | awk '{print $1}'`
set tabookeys=`echo $tabookeys | tr ' ' '|'`
set tabookeys="$tabookeys|change_prop"

# split dumpdir for pro/e if necc.
set dd_abs="$dumpdir"
set dd_rel=""
set sep=""
while (`echo "$dd_abs" | wc -c` > $wc_maxdirlen)
   set tmp="$dd_abs:t"
   if ("$dd_rel" != "") set sep="/"
   set dd_rel="$tmp$sep$dd_rel"
   set dd_abs="$dd_abs:h"
end

# Prefix trlbody for layout retrieval WITHOUT Pro/PROJECT
echo '#PROJECT'                      > $trlprj 
echo '#CREATE'                      >> $trlprj
echo "$dummy_proj_name"             >> $trlprj

# Prefix trlbody for layout retrieval WITH Pro/PROJECT
echo '#PROJECT'                      > $trlpprj
echo '#OPEN'                        >> $trlpprj
echo "#$dummy_proj_name"            >> $trlpprj

# Hardwire open prj for this project (-prj_name only)
set op_prjname="$prj_name"
if ("$op_prjname" == "") set op_prjname="$prj_conv"
if ("$op_prjname" != "") then
   sed s/$dummy_proj_name/$op_prjname/ $trlpprj > $trlpprj_r
endif

# Change to conv dir.
echo "$os_cmd"                       > $trlcd
echo "$cd_cmd"                      >> $trlcd
echo '__srcdir1__'                  >> $trlcd  # conv dir (abs)
echo "$cd_cmd"                      >> $trlcd
echo '__srcdir2__'                  >> $trlcd  # conv dir (rel, or '.')

# Change dir to cwd - used to get oos from trail files waiting for input
echo "$os_cmd"                       > $trlcdcwd
echo "$cd_cmd"                      >> $trlcdcwd
echo ''                             >> $trlcdcwd


# Generic restore sequence, will be used twice in creation of the
# conversion trail file to achieve OOS in the event of 'clip' menus etc.
# for import_mode this is the prt/draw import stubs - used once only.
if ("$obj_button" != "") then
   echo "$obj_button"                > $trlrstr  # New at 6.0
endif
if ($?import_mode) then

if ("$impfmt" == "prt") then
   # Part import commands.
   echo '#PART'                     >> $trlrstr
   echo '#IMPORT'                   >> $trlrstr
   echo '__object__'                >> $trlrstr # new part name
   echo '@ ok'                      >> $trlrstr 
   echo '#IGES IN'                  >> $trlrstr
   echo '__rsname__'                >> $trlrstr # igs file name
else
   # Drawing import commands.
   if ($?igsdrw_80) then
      echo '#DRAWING'                  >> $trlrstr
      echo '#IMPORT'                   >> $trlrstr
      echo '__object__'                >> $trlrstr # new drawing name
      echo '@ ok'                      >> $trlrstr 
      echo '#IGES IN'                  >> $trlrstr
      echo '__rsname__'                >> $trlrstr # igs file name
   else
      echo '#DRAWING'                  >> $trlrstr
      echo '#CREATE'                   >> $trlrstr
      echo '__object__'                >> $trlrstr # new drawing name
      echo '@ ok'                      >> $trlrstr 
      echo '#__rstrcmd__'              >> $trlrstr # papersize (misnomer)
      echo '#INTERFACE'                >> $trlrstr
      echo '#IMPORT'                   >> $trlrstr
      echo '#IGES'                     >> $trlrstr
      echo '__rsname__'                >> $trlrstr # igs file name
   endif
endif

else    # import_mode for trlrstr

echo '__object__'                   >> $trlrstr  # ex: #PART
echo '__rstrcmd__'                  >> $trlrstr  # ex: #RETRIEVE
echo '__rsname__'                   >> $trlrstr  # ex: p1.prt

endif   # import_mode for trlrstr

# Required between 2 restores in sketcher.
echo '#DONE'                         > $trldone

# Perform conversions for a particular object
echo "$os_cmd"                       > $trlbody
echo "$cd_cmd"                      >> $trlbody
echo "$dd_abs"                      >> $trlbody  # tmp dir (abs)
if ("$dd_rel" != "") then
   echo "$cd_cmd"                   >> $trlbody
   echo "$dd_rel"                   >> $trlbody  # tmp dir (rel,if necc)
endif
echo '#ENVIRONMENT'                 >> $trlbody
echo $storecmd                      >> $trlbody  # long or short term
echo $geomcmd                       >> $trlbody  # geom or no geom
if ("$ftab" == "yes") then
   echo "#FAMILY TAB"               >> $trlbody
   echo "#VERIFY"                   >> $trlbody
endif
echo '#DBMS'                        >> $trlbody

if ("$trlnum" >= "1151")  then
  echo '~ Activate `main_dlg_cur` `File.psh_save`'      >> $trlbody
else
  echo "$saveit_cmd"                  >> $trlbody
endif

if ("$ftab" == "yes") then
   echo '__svname__'                >> $trlbody
else
   echo ''                          >> $trlbody
endif

# What is needed to exit Pro/ENGINEER session.
echo '#EXIT'                         > $trlexit
echo 'y'                            >> $trlexit
   
# Create a dummy project under Pro/PROJECT for use converting .lays
cat "$trltop"                        > $trlpprjcr
echo '#PROJECT'                     >> $trlpprjcr
echo '#MANAGER'                     >> $trlpprjcr
echo '#CREATE PROJ'                 >> $trlpprjcr
echo '*'                            >> $trlpprjcr
echo "$dummy_proj_name"             >> $trlpprjcr
echo "$tmpdir"                      >> $trlpprjcr
echo '#EXIT'                        >> $trlpprjcr
echo 'y'                            >> $trlpprjcr

# Delete the dummy project under Pro/PROJECT
cat "$trltop"                        > $trlpprjdel
echo '#PROJECT'                     >> $trlpprjdel
echo '#MANAGER'                     >> $trlpprjdel
echo '#OPEN'                        >> $trlpprjdel
echo "#$dummy_proj_name"            >> $trlpprjdel
echo '#MANAGER'                     >> $trlpprjdel
echo '#DELETE PROJ'                 >> $trlpprjdel
echo 'y'                            >> $trlpprjdel
echo '#EXIT'                        >> $trlpprjdel
echo 'y'                            >> $trlpprjdel

# Report objs in a project.
echo "#REPORT"                       > $trlprep
echo "#TREE"                        >> $trlprep
echo "#FILE"                        >> $trlprep

# Convert a project to Rel 8.0
if ("$prj_conv" != "") then
   echo '#MANAGER'                  >> $trlprjcnv
   echo '#CONVERT PROJ'             >> $trlprjcnv
   echo 'update to 8.0'             >> $trlprjcnv
endif

# PROCESS WHICH RUNS IN BACKROUND AND KILLS PROCMD AFTER DELAY
set killer="$tmpdir/killer"
echo '#\!/bin/csh -f'                > $killer
echo 'sleep $1'                     >> $killer
echo $ps_cmd \>\& /tmp/killer.\$\$  >> $killer
echo set propid=\`cat /tmp/killer.\$\$ \| grep \"$execname\" \| awk \'\{print \$$pidcol\}\'\`                       >> $killer
echo rm -f /tmp/killer.\$\$         >> $killer
echo 'if ("$propid" != "") then'    >> $killer
echo '   kill -9 $propid'           >> $killer
echo '   if ($?PCVT_KILLMSG) then'  >> $killer  
echo '      echo "$PCVT_KILLMSG" |& tee -a '$logfile  >> $killer
echo '   endif'                     >> $killer
echo 'endif'                        >> $killer
chmod +x $killer

# AWK SCRIPT TO GET DIR/FILE.EXT
set dotawk="$tmpdir/dot.awk"
cat << CAT_EOF > $dotawk
{
 full=\$0
 nfull=split(full,afull,"/")
 fev=afull[nfull]
 split(fev,afev,".")
 fe = afev[1] "." afev[2]
 i=1
 for (i in afull)
    {
     if (i == nfull) continue
     printf "/%s", afull[i]
     i++
    }
  printf "%s\n", fe
}
CAT_EOF


# GENERATE LIST OF FILES TO CONVERT
unset remote_prjhomedir
if ("$list" != "") then
   cat $list | sed "s+^+$startdir/+" > $convlist.tmp
else if ("$prj_name" != "" || "$prj_conv" != "") then
  cd $tmpdir
  set trailfile="$trl_tmpname:t"
  set nonomatch
  rm -f ${trailfile}*
  unset nonomatch
  cat $trltop $trlpprj_r $trlprep $trlexit > $trl_tmpname
  set nonomatch
  rm -f $prj_repfile
  unset nonomatch

  $procmd $runmode $gfxnum 1 $trailfile >& /dev/null
  set pro_status="$status"

  set nonomatch
  set repfile=`$ls_cmd $prj_repfile |& tail -1`
  unset nonomatch
  # should never happen 
  if (`echo "$repfile" | grep "$nonoline" | wc -c` > 0 || $pro_status) then
     echo ""
     echo "ERROR:  Cannot generate tree report for project '$op_prjname'."
     echo "        Check the project name and/or Pro/PROJECT server availability."
     goto QUICK_EXIT
  endif

  # GET THE PROJECT MACH AND DIR
  set path=($path /etc /usr/etc)  # for ping
  set prjname_uc=`echo $op_prjname | tr '[a-z]' '[A-Z]'`
  set servfile="/etc/dmsservers.txt"
  set num_lines="`cat $servfile | wc -l | tr -d ' '`"
  unset found
  set curserv=1
  while ($curserv <= $num_lines)
     set raw=`sed -n "$curserv p" $servfile`
     @ curserv++ 
     set servname=`echo "$raw" | awk '{print $1}'`
     set acc=`echo "$raw" | awk '{print $2}'`
     set arch=`echo "$raw" | awk '{print $4}'`

     # Ping servname to see if it's reachable
     if ($mc_type =~ sun* || $mc_type == "dg") then
        if (`ping $servname 5 |& egrep "(unknown|find)" | wc -c` > 1) then
           set loss = ""
        else if (`ping $servname 5 | fgrep alive | awk '{print $3}'` != "alive") then
           set loss = "100%"
        else
           set loss = "0%"
        endif
     else
        set ping_pars="$servname -n 2"
        if ($mc_type =~ sgi*) set ping_pars="-n -c 2 $servname"
        set loss = `ping $ping_pars |& fgrep loss | awk '{print $7}'`
     endif
     if ($loss == "" || $loss == "100%") continue

     if ("$acc" != "direct") set remcmd="$rsh_cmd $servname"
     set prjhomemach=`$remcmd cat $arch |& awk '$1 == "'$prjname_uc'" {print $2}' | tr '[A-Z]' '[a-z]'`
     if ("$prjhomemach" != "") then
        set prjhomedir=`$remcmd cat $arch | awk '$1 == "'$prjname_uc'" {print $5}' | tr '[A-Z]' '[a-z]'`
        set found
        break 
     endif
  end
  if (! $?found) then
     echo ""
     echo "ERROR:  Cannot determine the project directory."
     goto QUICK_EXIT
  endif

  set targetdir="$prjhomedir"
  if ("$prjhomemach" != `hostname`) set remote_prjhomedir
  
  # Allow 50 nodes (dirs) deep - error if deeper.
  set col=("" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" " " "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "")
  set num_lines="`cat $repfile | wc -l | tr -d ' '`"
  set curline=3
  while ($curline <= $num_lines)
     set numchar=`sed -n "$curline p" $repfile | wc -c`
     set obj=`sed -n "$curline p" $repfile | tr -d ' '`
     @ curline++ 
     set numobj=`echo "$obj" | wc -c`
     @ numsp = ($numchar - $numobj)
     set level=`echo "$numsp/10" | bc`  # i.e. num tabs
     @ level++                          # +1 for colnum
     if ("$level" > "50") then
        echo "ERROR:  proj node nesting > 50, skipping $obj"
        continue
     endif
     echo -n "$prjhomedir/" >> ${repfile}_t1
     set col[$level]="$obj"
     set i=1
     while ($i < $level)
        echo -n $col[$i]\/ >> ${repfile}_t1
        @ i++
     end
     echo "$col[$level]" >> ${repfile}_t1
  end

  # Filter junk out - just want things ending in PTC exts (no vers)
  egrep '.('$exts_re')$' ${repfile}_t1 > $convlist.real
else
   cd $startdir
   if ("$descend" == "yes") then
      find $startdir -name '*' -type d -print >> $convlist.dirs
   else
      echo $startdir > $convlist.dirs
   endif
   set num_lines="`cat $convlist.dirs | wc -l | tr -d ' '`"
   set curline=1
   while ($curline <= $num_lines)
     set dir=`sed -n "$curline p" $convlist.dirs`
     set nonomatch
     foreach type ($exts)
        $ls_cmd $dir/*.$type   >>& $convlist.files
        $ls_cmd $dir/*.$type.* >>& $convlist.files
     end
     unset nonomatch
     @ curline++ 
   end 
   # Some dirs may not have contained any ptcfiles...
   grep -v "$nonoline" $convlist.files > $convlist.tmp
endif

# REMOVE VERSION NUMBERS FROM LIST (except prj report - no vers)
if ("$prj_name" == "" && "$prj_conv" == "") then
   awk -f $dotawk $convlist.tmp | uniq >& $convlist.real
endif

# CHECK THAT AT LEAST ONE FILE IS TO BE CONVERTED
set num_lines="`cat $convlist.real | wc -l | tr -d ' '`"
if ($num_lines == "0") then
   echo ""
   echo ""
   echo "INFORMATION:  No files to convert (of the following type)  - " |& tee -a $logfile
   echo "$ptcfiles" |& tee -a $logfile
   goto QUICK_EXIT
endif
echo ""
echo ""

####################################################################
# this section for prj_conv only

if ("$prj_conv" != "") then
   if ($?nlo_env) sleep $nloserv_delay
   cd $dumpdir
   cat $trltop $trlpprj_r $trlprjcnv $trlexit > __cv__.trl
   echo "CONVERTING PROJECT $prj_conv"
   echo ""
   unset badprostatus
   $procmd $runmode $gfxnum 1 __cv__.trl >& $dumpdir/${prj_conv}_msg
   if ($status != 0) set badprostatus

   if ($?badprostatus) then
      echo "# ERROR - COULD NOT CONVERT PROJECT $prj_conv" >> $logfile
      echo "# Read messages in $initialdir/${prj_conv}_msg" >> $logfile
      cp $dumpdir/${prj_conv}_msg $initialdir
      rm -f $dumpdir/${prj_conv}_msg
   else
      echo "# CONVERTED PROJECT $prj_conv" >> $logfile
   endif
   echo "" >> $logfile

   goto QUICK_EXIT
endif

####################################################################


#
#                  PROCESS THE CONVERSION LIST
#

# FILTER OUT NON-CONVERTS AND ESTIMATE CONVERSION SIZE
echo ""
set msg="1st pass - estimate conversion space requirements"
set numchars=`echo "$msg" | wc -c`
@ numchars--
echo "$msg"
repeat $numchars echo -n "-"
echo ""
echo ""
unset files_exist
set shortsize=0
set longsize=0
set curline=1
set num_lines="`cat $convlist.real | wc -l | tr -d ' '`"

# PRJ_NAME - Skip if this is a remote project
if ("$prj_name" != "" && $?remote_prjhomedir) then
   cp $convlist.real $convlist
   @ curline = ($num_lines + 10)
endif

while ($curline <= $num_lines)
   set convfullfile=`sed -n "$curline p" $convlist.real`
   set convdir="$convfullfile:h"
   @ curline++

   # CHECK FILE EXISTS
   set nonomatch
   set exist=`$ls_cmd $convfullfile* | grep -v '_msg' |& tail -1`
   unset nonomatch
   if (! -e "$exist" || `echo "$exist" | grep "$nonoline" | wc -c` > 0 ) then
      echo "# FILE DOES NOT EXIST" >> $logfile
      echo "# $convfullfile" >> $logfile
      echo "" >> $logfile
      continue
   endif
   set convfullfilev=`$ls_cmd $convfullfile* |& egrep '[a-z]*.[a-z]*[0-9]?$' | sort -t. +2n | tail -1`
   if ("$convfullfilev" == "") set convfullfilev="$convfullfile"
   set convfilev="$convfullfilev:t"

   # AT LEAST ONE FILE EXISTS
   set files_exist

   # CHECK FORMAT
   set noglob
   if ("$unixflavor" == "sys5" || "$mc_type" == "sun4_solaris") then
      set bott="`tail -100c $convfullfilev | od -c | cut -f2- -d' ' -s`" 
   else
      set bott="`tail -100c $convfullfilev | od -c | colrm 1 8`" 
   endif
   set bott=`echo $bott | sed s/' '/''/g`
   unset noglob

   echo "$bott" |& grep "$shorttypetag" >& /dev/null
   if ($status == 0) then
      set format="short"
   else
      echo "$bott" |& grep "$longtypetag" >& /dev/null
      if ($status == 0) then
         set format="long"
      else
         set format="unknown"
      endif
   endif

   if ("$forceconvert" == "no") then
      if ("$storemode" == "$format") then
         echo "# NO CONVERSION NECCESSARY" >> $logfile
         echo "# $convfullfile" >> $logfile
         echo "" >> $logfile
         continue
      endif
   endif

   if ($?full_mode && "$prjdir" == "no" && "$prj_name" == "") then
      set noglob
      set top2lines=`sed -n "1,2 p" $convfullfilev`
      unset noglob
      if (`echo "$top2lines" | grep "$rev8prjtag" | wc -l` != 0) then
         echo "# Pro/PROJECT FILE (REV. 8) IGNORED" >> $logfile
         echo "# $convfullfile" >> $logfile
         echo "" >> $logfile
         continue
      endif
   endif

   if ("$prjdir" == "no" && "$prj_name" == "") then
      set prjutil_status="$prjutil_noaction"  # Assume no prj header
      if ($?prjutil_exists) then
         cd $convdir
         $prjutil split $convfilev $dumpdir >& /dev/null
         set prjutil_status="$status"
      endif
      if ("$prjutil_status" == "$prjutil_good") then
         echo "# Pro/PROJECT FILE IGNORED" >> $logfile
         echo "# $convfullfile" >> $logfile
         echo "" >> $logfile
         continue
      endif
   endif

   set size=`du -s $convfullfilev | awk '{print $1}'`
   if ("$format" == "short") then
      @ shortsize = ( $shortsize + $size )
   else
      @ longsize = ( $longsize + $size )
   endif 
   echo "$convfullfile" >> $convlist
end


# CHECK LIST (STILL) HAS ENTRIES
set num_lines="0"
if (-e $convlist) set num_lines="`cat $convlist | wc -l | tr -d ' '`"
if ($num_lines == "0") then
   if ($?files_exist) then
      echo "INFORMATION:  All files are already '$storemode'" |& tee -a $logfile
      echo "Use the '-f' flag to force conversion" |& tee -a $logfile
      echo ""
   else
      echo "ERROR:  No files found to convert." |& tee -a $logfile
      echo "" |& tee -a $logfile
   endif
   goto QUICK_EXIT
endif

if ("$prj_name" != "") then
   cp $convlist $convlist.tmp
   sed s+$prjhomedir/++g $convlist.tmp > $convlist 
   rm -f $convlist.tmp
endif

# WARN IF NOT ENOUGH DISK SPACE BASED ON THE ESTIMATION
set dfline=`$df_cmd $targetdir |& tail -1 |& sed s/'):'//g`
set top=`echo "$dfline" | awk '{print $'$mcol'}'`
set avail=`echo "$dfline" | awk '{print $'$fcol'}'`
unset space_unknown
if (`echo $avail | egrep -c '^[0-9]+$'` == 0) set space_unknown

if ("$storemode" == "long") then
   if ("$geommode" == "nogeom") then
      set estexpr="($shortsize * $s_l) + $longsize"
   else
      set estexpr="($shortsize * $s_lg) + ($longsize * $l_lg)"
   endif
else
   if ("$geommode" == "nogeom") then
      set estexpr="($longsize * $l_s) + $shortsize"
   else
      set estexpr="($longsize * $l_sg) + ($shortsize * $s_sg)"
   endif
endif

set estsize=`echo "scale=3; $estexpr" | bc | awk -F. '{print $1}'`
set origsize=`echo "$longsize + $shortsize" | bc`

unset askcont
if ($?space_unknown) then
   if (! $?remote_prjhomedir) then
      echo ""
      echo ""
      echo "WARNING:  unable to determine free space in $targetdir"
      echo "          Only continue if you are sure there is enough space."
      echo ""
      set askcont
   endif
else if ("$avail" < "$estsize") then
   echo ""
   echo ""
   echo "WARNING:  available space (on $top)   $avail $dfunits"
   echo "          estimated conversion space  $estsize $dfunits" 
   echo "          If you continue you risk filling the disk."
   echo ""
   set askcont
endif

if ($?askcont) then
   echo -n "Do you wish to continue [n] ?: "
   set ans="$<"
   if ("$ans" == "") set ans="n"
   if ("$ans" == "n" || "$ans" == "no") goto QUICK_EXIT
   echo ""
   echo ""
endif

echo ""
if ("$prj_name" != "" && $?remote_prjhomedir) then
   echo "Cannot determine space requirements." |& tee -a $logfile
   echo "$name should be run on the project home machine ($prjhomemach)." |& tee -a $logfile
else
   echo "Total size of files to convert:           $origsize ($dfunits)"
   echo "Total estimated size of converted files:  $estsize ($dfunits)"
   echo ""  |& tee -a $logfile
   echo "#" >> $logfile
   echo "# 1st pass size summary ($dfunits):   Original=$origsize    Estimated=$estsize" >> $logfile
   echo "#" >> $logfile
endif
echo ""  |& tee -a $logfile

####################################################################

# Preserve some parameters
set sv_convlist="$convlist"
set sv_startdir="$startdir"
set sv_targetdir="$targetdir"

if ("$prjdir" == "yes") then
   set warnings
   set curline=1
   while ($curline <= $num_lines)
      set convfullfile=`sed -n "$curline p" $convlist`
      @ curline++
      set convfile="$convfullfile:t"
      set convdir="$convfullfile:h"
      cd $convdir
      set nonomatch
      set convfilev=`$ls_cmd $convfile* |& egrep '[a-z]*.[a-z]*[0-9]?$' | sort -t. +2n | tail -1`
      unset nonomatch
      if ("$convfilev" == "") set convfilev="$convfile"
   
      # get delta of $startdir, $convdir
      set delta=`echo "$startdir $convdir" | awk '{s=$1; c=$2; print substr(c,length(s)+2)}'`
      if ("$delta" != "") then
	 set destdir="$prvstartdir/$delta"
      else
         set destdir="$prvstartdir"
      endif
      # make sure destdir exists
      set build="$prvstartdir"
      set numdirs=`echo $delta | tr '/' ' ' | wc -w`
      set i=1
      while ("$i" <= "$numdirs")
         set newdir=`echo $delta | awk -F/ '{print $'$i'}'`
         @ i++
         set build="$build/$newdir"
         if (! -d $build) mkdir $build
      end 

      cd $convdir
      $prjutil split $convfilev $destdir >& /dev/null
      set prjutil_status="$status"
      switch ($prjutil_status)  
         case $prjutil_noaction
            # This is ok but 'expensive'
            cp $convfilev $destdir
            echo "$dumheadstr" > $destdir/${convfilev}_h
         breaksw

         case $prjutil_good
            mv -f $destdir/${convfilev}_b $destdir/$convfilev
         breaksw

         case $prjutil_bad
            echo "# ERROR:  $convdir/$convfilev - invalid Pro/ENGINEER file" >> $logfile
            continue    # DO NOT PROCESS
         breaksw

         default
            echo "# ERROR:  (internal error split $convfilev unknown status)" >> $logfile
            continue    # DO NOT PROCESS
         breaksw
      endsw

      # copy the config.pro if not already done for this dir
      if (-e $convdir/config.pro) then
         if (! -e $destdir/config.pro) cp $convdir/config.pro $destdir/config.pro
      endif

      echo "$destdir/$convfile" >> $convlist.priv
   end

   # Modify some parameters for intermediate processing
   set convlist="${convlist}.priv"
   set startdir="$prvstartdir"
   if ("$sv_startdir" == "$sv_targetdir") then
      set targetdir="$prvstartdir"
   else
      set targetdir="$prvtargetdir"
   endif
endif

####################################################################


echo ""
set msg="2nd pass - Process the files (in $convlist)"
set numchars=`echo "$msg" | wc -c`
@ numchars--
echo "$msg"
repeat $numchars echo -n "-"
echo ""
echo ""

# CONFIGURE FOR PROJECT MODULE TYPES
set rstrprjfile=""
if ("$prj_name" == "") then
   set lays=`cat $convlist | grep '\.lay' | wc -c`
   set prjs=`cat $convlist | grep '\.prj' | wc -c`
   if ("$lays" > 0 || "$prjs" > 0) then
      if ($?dms_env) then          # Reqd Pro/PROJECT file.
         set rstrprjfile="$trlpprj"
      else
         set rstrprjfile="$trlprj"
      endif
   endif
endif

#
#                   CATCH INTERRUPTS AND CLEANUP
#
# move the following with care - destination depends on vars being set.
onintr CLEANUP


# IF Pro/PROJECT - CREATE A DUMMY PROJECT FOR LAYOUT RETRIVAL.
if ($?dms_env && "$rstrprjfile" != "") then
   cd $tmpdir
   set trailfile="$trlpprjcr:t"
   $procmd $runmode $gfxnum 1 $trailfile >& /dev/null

   # Allow time for server to create proj.
   echo "INFORMATION - waiting $dmsserv_delay secs for Pro/PROJECT server (create)."
   sleep $dmsserv_delay
endif

# CONSTRUCT CONFIG.PRO FOR 'NONE' OR A SPECIFIC FILENAME
unset test_cfgfile
cp $my_cfgfile $realcfg
if ("$user_cfgfile" != "existing" && "$user_cfgfile" != "none") then
   if (-e $user_cfgfile) then
      cat $user_cfgfile | egrep -v "($tabookeys)" >> $realcfg
      if (`diff $realcfg $my_cfgfile | wc -l` != 0) set test_cfgfile
   endif
endif


# WALK THRU THE CONVERSION LIST
set last_convdir=""
set convdir=""
set num_lines="`cat $convlist | wc -l | tr -d ' '`"
set curline=1
while ($curline <= $num_lines)
   set convfullfile=`sed -n "$curline p" $convlist`
   set filenum="$curline"
   @ curline++
   set convfile="$convfullfile:t"
   set convdir="$convfullfile:h"
   if ("$convdir" == "$convfile") set convdir=""  # can only occur w/ -prj_name
   set convexten=`echo $convfile | awk -F. '{print $2}'`
   set convnameonly=`echo $convfile | awk -F. '{print $1}'`
   set disp_convdir="$convdir"
   if ("$prjdir" == "yes") set disp_convdir=`echo "$convdir" | sed s+$startdir+$sv_startdir+`

   # CONSTRUCT CONFIG.PRO FOR 'EXISTING'
   if ("$convdir" != "$last_convdir" && "$user_cfgfile" == "existing") then
      set last_convdir="$convdir"
      rm -f $realcfg
      cp $my_cfgfile $realcfg
      if (-e $convdir/config.pro) cat $convdir/config.pro | egrep -v "($tabookeys)" >> $realcfg
      unset test_cfgfile
      if (`diff $realcfg $my_cfgfile | wc -l` != 0) set test_cfgfile
   endif

   # CHECK CONFIG FILE WON'T HANG PROE
   if ($?test_cfgfile) then
      unset test_cfgfile
      cd $dumpdir  
      cp $realcfg $dumpdir/config.pro
      cp $trlend $dumpdir/trlend.txt
      echo ""
      echo "            --- CHECKING THE CONFIG FILE ---"

      setenv PCVT_KILLMSG ""
      $killer 60 &
      unsetenv PCVT_KILLMSG
      $procmd $runmode $gfxnum 1 trlend.txt >& /dev/null
      set prostatus="$status"
      # STOP KILLER PROCESS AND ITS SLEEP PROCESSES IF NECC.
      $ps_cmd >& $tmpdir/ps.$pid
      set killpid=`cat $tmpdir/ps.$pid | grep "$killer" | awk '{print $'$pidcol'}'`
      if ("$killpid" != "") then
         set sleeppid=`$ps_cmd | awk '$'$ppidcol' == "'$killpid'" {print $'$pidcol'}'`
         (kill -9 $killpid)     # shell in case process non-existent
         (kill -9 $sleeppid)    # shell in case process non-existent
       endif
       rm -f $tmpdir/ps.$pid

      if ($prostatus != 0 || ! -e trail.txt.1) then
         cp $my_cfgfile $realcfg  # ignore everything from user's config.pro
         echo "# ERROR: check $convdir/config.pro for errors." >> $logfile
         echo "ERROR: check $convdir/config.pro for errors."
         echo "" |& tee -a $logfile
      else
         echo "CONFIG FILE OK."
         echo ""
      endif


   endif

   echo ""
   echo "PROCESSING FILE ${filenum} OF $num_lines   -  $prj_name $disp_convdir/$convfile"

   if ("$prj_name" == "") then
      cd $convdir
      set nonomatch
      set convfilev=`$ls_cmd $convfile* |& egrep '[a-z]*.[a-z]*[0-9]?$' | sort -t. +2n | tail -1`
      unset nonomatch
      if ("$convfilev" == "") set convfilev="$convfile"

      # CHECK FILE (STILL!) EXISTS
      if (`echo "$convfilev" | grep "$nonoline" | wc -c` > 0) then
         echo "# FILE DOES NOT EXIST" >> $logfile
         echo "# file ${filenum} - $convdir/$convfile" >> $logfile
         echo "" |& tee -a $logfile
         continue
      endif

      # CHECK IF FILE HAS ALREADY BEEN PROCESSED
      grep -v '#' $logfile | grep $convfullfile >& /dev/null
      if ($status == 0) then
         echo "# CONVERTED ABOVE" >> $logfile
         echo "# file ${filenum} - $convdir/$convfile" >> $logfile
         echo "" |& tee -a $logfile
         continue
      endif
   endif

   # CHECK MINIMUM DISK SPACE
   if ("$min_space" != "0" && ! $?space_unknown) then
      set kb_avail=`$df_cmd $targetdir |& tail -1 |& sed s/'):'//g |& awk '{print $'$fcol'}'`
      if ("$dfunits" == "blocks") set kb_avail=`echo $kb_avail/2 | bc`
      if ("$kb_avail" < "$min_space") then
         echo "" |& tee -a $logfile
         echo "# ABORTING:  available space in $top = $kb_avail Kb" |& tee -a $logfile
         echo "#            Space cutoff is $min_space Kb" |& tee -a $logfile
         goto QUICK_EXIT
      endif
   endif

   # CLEAN DUMP DIR
   set nonomatch
   rm -f $dumpdir/* $fetchdir/* >& /dev/null
   unset nonomatch

   if (! $?import_mode) then
      set i=1
      set buttonnum=0
      while ($i <= $#exts)
         if ($convexten == $exts[$i]) set buttonnum=$i
         @ i++
      end
      if ($buttonnum == 0) then
         echo "ERROR:  file $convfile does not have a Pro/ENGINEER button"
         continue 
      endif
      set objcmd=$buttons[$buttonnum]
   endif

   # SET CONVDIR PATHS
   if ("$prj_name" != "") then    # goto fetch dir
      set cv_abs="../fetch"
      set cv_rel="."
   else if ("$maxdirlen" == "") then
      set cv_abs="$convdir"
      set cv_rel="."
   else
      set cv_abs="$convdir"
      set cv_rel=""
      set sep=""
      while (`echo "$cv_abs" | wc -c` > $wc_maxdirlen)
         set tmp="$cv_abs:t"
         if ("$cv_rel" != "") set sep="/"
         set cv_rel="$tmp$sep$cv_rel"
         set cv_abs="$cv_abs:h"
      end
      if ("$cv_rel" == "") set cv_rel="."    # no rel. cd
   endif

   # SET RETRIEVE COMMAND, HEADER FILE, NAME-HEADER, EXTRA RSTR CMDS
   set prjheader=""
   set nameheader=""
   set rstrcmd="#RETRIEVE"
   set rstrextra=""
   if ($convexten == "lay") then 
      set prjheader="$rstrprjfile"
   endif
   if ($convexten == "prj") then
      set nameheader="#"
      if ($?dms_env) set rstrcmd="#OPEN"
   endif
   if ($convexten == "sec") then
      set rstrextra="$trldone"
   endif
   set subs_rsname="${nameheader}${convnameonly}"
   set subs_svname="$convnameonly"

   if ("$prj_name" == "") then
      set trlpfet=""
      set trlpsub=""
      set trlpunf=""
   else
      set prjheader="$trlpprj_r"
      # Must 'dynamically' create these fragments for each obj.
      rm -f $trlpfet $trlpsub $trlpunf
      echo "#FETCH"                           >  $trlpfet
      echo "$modify_keywd"                   >> $trlpfet
      echo "#SUBMIT"                          >  $trlpsub
      echo "$unfetch_keywd"                   >  $trlpunf

      set numfields=`echo "$convfullfile" | awk -F/ '{print NF}'`
      set i=1
      while ($i < $numfields)
         set field=`echo $convfullfile | awk -F/ '{print $'$i'}'`
         echo "#/$field" |& tee -a $trlpfet $trlpsub $trlpunf >& /dev/null
         @ i++
      end
      set field=`echo $convfullfile | awk -F/ '{print $'$numfields'}'`
      echo "#$field" |& tee -a $trlpfet $trlpsub $trlpunf >& /dev/null
      echo "could not convert"               >> $trlpunf
   endif

   cd $dumpdir  

   # PLACE UNWRITABLE CORE FILES
   rm -f core
   touch core
   chmod 000 core
   # core file could get dumped in retr dir.
   if ("$prj_name" == "") then
      set retdir="$convdir"
   else
      set retdir="$fetchdir"
   endif
   if ( ! -e $retdir/core) then
      rm -f $retdir/core >& /dev/null
      touch $retdir/core >& /dev/null
      chmod 000 $retdir/core >& /dev/null
   endif

   # CONFIGURE PARAMETERS FOR PROIMP MODE
   set trlrstr1="$trlrstr"
   if ($?import_mode) then
      set trlrstr2=""
      set objcmd="$convnameonly"
      set rstrcmd="$papersize"      # only used for drawings at 7.0
      set subs_rsname="$convfile"
   else
      set trlrstr2="$trlrstr"
   endif

   # CONFIGURE THE TEMPLATE
   set trls="$trltop $prjheader $trlcd $trlrstr1 $rstrextra $trlrstr2 $trlbody $trlexit"
   set nonomatch
   rm -f __cv__.trl* >& /dev/null
   unset nonomatch
   cat $trls | sed s/__rstrcmd__/$rstrcmd/ | sed s/__object__/$objcmd/ | sed s+__rsname__+$subs_rsname+ | sed s+__svname__+$subs_svname+ | sed s+__srcdir1__+$cv_abs+ | sed s+__srcdir2__+$cv_rel+ > __cv__.trl

   # COPY CONFIG FILE TO DUMPDIR
   rm -f config.pro
   cp $realcfg config.pro
   if ("$ftab" == "yes") then
      echo "search_path $convdir" >> $dumpdir/config.pro
   endif
  
   #
   # IF PRJ_NAME DO A FETCH AND ENSURE IT SUCCEEDS
   #
   unset badprostatus
   if ("$prj_name" != "") then
      unset fetch_ok
      # PAUSE FOR NLO IF NECC.
      if ($?nlo_env) sleep $nloserv_delay
      cd $dumpdir
      set trailfile="$trl_tmpname:t"
      set nonomatch
      rm -f ${trailfile}*
      unset nonomatch
      set trls="$trltop $trlpprj_r $trlcd $trlpfet $trlcdcwd $trlexit"
      cat $trls | sed s+__srcdir1__+$cv_abs+ | sed s+__srcdir2__+$cv_rel+ > $trl_tmpname
      cp $trl_tmpname .

      $procmd $runmode $gfxnum 1 $trailfile >& $dumpdir/${convfile}_msg
      if ($status != 0) set badprostatus

      touch $fetchdir/dummy.prt_msg
      if (`$ls_cmd $fetchdir/{$ptcfiles} |& grep -v '_msg' | wc -l` == 0 || $?badprostatus) then
         set badprostatus
      else
         set nonomatch
         rm -f trail.txt* $dumpdir/${convfile}_msg
         unset nonomatch
         set fetch_ok
      endif
   endif

   if (! $?badprostatus) then
      # PAUSE FOR NLO IF NECC.
      if ($?nlo_env) sleep $nloserv_delay

      # INITIATE KILLER AND RUN THE TRAIL FILE
      if ("$killdelay" != 0) then
         echo Start Terminator
         setenv PCVT_KILLMSG "# *** TERMINATED after $killdelay mins ***"
         $killer $killdelay_secs & 
         unsetenv PCVT_KILLMSG
      endif

      unset badprostatus
      $procmd $runmode $gfxnum 1 __cv__.trl >& $dumpdir/${convfile}_msg
      if ($status != 0) set badprostatus

      # STOP KILLER PROCESS AND ITS SLEEP PROCESSES IF NECC.
      if ("$killdelay" != 0) then
         $ps_cmd >& $tmpdir/ps.$pid
         set killpid=`cat $tmpdir/ps.$pid | grep "$killer" | awk '{print $'$pidcol'}'`
         if ("$killpid" != "") then
            set sleeppid=`$ps_cmd | awk '$'$ppidcol' == "'$killpid'" {print $'$pidcol'}'`
            echo Stop Terminator
            (kill -9 $killpid)     # shell in case process non-existent
            (kill -9 $sleeppid)    # shell in case process non-existent
          endif
          rm -f $tmpdir/ps.$pid
      endif

      set nonomatch
      rm -f __cv__.trl* trail.txt* core $convdir/core >& /dev/null
      if ("$prjheader" != "") rm -f $dummy_proj_name.prj* >& /dev/null
      unset nonomatch
   endif

   if ($?badprostatus) then
      echo "# WARNING - Pro/ENGINEER EXITED WITH ERROR" >> $logfile
      if ($?nlo_env) sleep $nloserv_timeout
   endif

   cd $dumpdir        # should already be there
   set msg_dir="$convdir"
   if ("$prj_name" != "") set msg_dir="$initialdir"
   touch dummy.prt_msg
   set nonomatch
   if ("$prjheader" != "") rm -f $dummy_proj_name.prj* >& /dev/null
   if (`$ls_cmd $cwd/{$ptcfiles_out} |& grep -v '_msg' | grep -v "$nonoline" | wc -l` == 0 || $?badprostatus) then
      echo "# COULD NOT CONVERT" >> $logfile
      echo "# file ${filenum} - $prj_name $convdir/$convfile" >> $logfile
      echo "# Read messages in $msg_dir/${convfile}_msg" >> $logfile
      echo "" |& tee -a $logfile
      mv -f $dumpdir/${convfile}_msg $msg_dir >& /dev/null
      if ($status != 0) mv -f $dumpdir/${convfile}_msg $initialdir
      unset conv_ok
   else
      echo "# CONVERTED" >> $logfile
      echo "# file ${filenum} - $prj_name $convdir/$convfile" >> $logfile 
      if ("$prj_name" != "") echo "" |& tee -a $logfile
      rm -f $dumpdir/${convfile}_msg
      set conv_ok
   endif
   rm -f $dumpdir/dummy.prt_msg
   unset nonomatch


   if ("$prj_name" == "") then
      if (! $?conv_ok) continue
   else
      if (! $?fetch_ok) continue

      if ($?conv_ok) then
         set prjaction="$trlpsub"
      else
         set prjaction="$trlpunf"
      endif

      cd $dumpdir
      set trailfile="$trl_tmpname:t"
      set nonomatch
      rm -f ${trailfile}*
      unset nonomatch
      cat $trltop $trlpprj_r $prjaction $trlexit > $trl_tmpname
      cp $trl_tmpname .
      $procmd $runmode $gfxnum 1 $trailfile >& /dev/null
      continue
   endif

   # SET THE NAME OF THE TARGET DIR IF NECC.
   if ("$targetdir" == "$startdir") then 
      set destdir="$convdir"
   else
      set destdir="$targetdir"
   endif
   set delta=""
   if ("$descend" == "yes" && "$targetdir" != "$startdir") then
      set destdir="$targetdir"
      set root=$startdir
      set sub=$convdir
      if ($sub =~ $root*) then           # Find targetdir/? ...
         while ("$sub" != "$root")
            set tail="$sub:t/"
            set delta="$tail$delta"
            set sub="$sub:h"
         end
	 set delta="$delta:h"
         if ("$delta" != "") set destdir="$targetdir/$delta"
      else
         set destdir="$targetdir/NEW"      # ...else put in newroot/NEW
	 set delta="NEW"
      endif
   endif


   foreach f ($ptcfiles_out_sp)
      set newfile=`echo $f | awk -F. '{print $1,".",$2}' | sed s/' '/''/g` 
      # CHECK IF FILE HAS ALREADY BEEN PROCESSED
      grep -v '#' $logfile | grep $convdir/$newfile >& /dev/null
      if ($status == 1) then
         set dest_v="1"

         # NOT INTERESTED IN ANY FILE WHICH DID NOT ORIGINALLY EXIST
         if (! $?import_mode) then
            set nonomatch
            set exist=`$ls_cmd $convdir/$newfile* |& tail -1` 
            unset nonomatch
            if (`echo "$exist" | grep "$nonoline" | wc -c` > 0) continue
         endif

         set save_cwd=`pwd`
         cd $convdir       # avoids dots in dir path problem
         set conv_v=`$ls_cmd $newfile* |& egrep '[a-z]*.[a-z]*[0-9]?$' | sort -t. +2n | tail -1 | awk -F. '{print $3}'` 
         cd $save_cwd
         if ($destdir == $convdir) then 
            @ dest_v = ( $conv_v + 1 )
         endif
         set destfile="$newfile.$dest_v" 

         if ($?import_mode) then
            set origfile=`$ls_cmd $convdir/$convfile* |& grep -v '_msg'  | sort -t. +2n | tail -1`
         else
            if ("$conv_v" == "") then
               set d_conv_v=""
            else
               set d_conv_v=".$conv_v"
            endif
            set origfile="$convdir/$newfile$d_conv_v"
         endif
         echo "$origfile  $destdir/$destfile" >> $logfile

	 # ENSURE DESTINATION DIR EXISTS
         set build="$targetdir"
	 set numdirs=`echo $delta | tr '/' ' ' | wc -w`
	 set i=1
         while ("$i" <= "$numdirs")
            set newdir=`echo $delta | awk -F/ '{print $'$i'}'`
            @ i++
            set build="$build/$newdir"
	    if (! -d $build) mkdir $build
         end 
         cp $newfile.1 $destdir/$destfile

         if ("$purgefiles" == "yes") then
            cd $destdir
            purge $newfile
            cd $dumpdir
         endif

      endif
   end

   echo "" |& tee -a $logfile

   if ("$ftab" == "yes") then
      set convfiletst="$convfile:r.tst"
      if (-e $convfiletst) cp $convfiletst $destdir
      set convdirmnu="$convdir/$convdir:t.mnu"
      if (-e $convdirmnu) cp $convdirmnu $destdir
   endif

   # CLEAN DUMP DIR
   set nonomatch
   rm -f $dumpdir/* $fetchdir/* >& /dev/null
   unset nonomatch

end

#
#                 REMOVE TEMPORARY FILES
#
goto NORMAL_PATH
CLEANUP:
echo ""
echo "*** INTERRUPT ***                                          *** INTERRUPT ***"
echo "*** INTERRUPT ***   Please wait for cleanup and exit ...   *** INTERRUPT *** "
echo "*** INTERRUPT ***                                          *** INTERRUPT ***"
echo ""
NORMAL_PATH:

# IF Pro/PROJECT DUMMYPROJ WAS CREATED DELETE IT NOW
if ($?dms_env && "$rstrprjfile" != "") then
   cd $tmpdir
   set trailfile="$trlpprjdel:t"
   $procmd $runmode $gfxnum 1 $trailfile >& /dev/null

   # Allow time for server to create proj.
   echo "INFORMATION - waiting $dmsserv_delay secs for Pro/PROJECT server (delete)."
   sleep $dmsserv_delay
endif

#
#                 WRITE TAIL INFO TO LOGFILE
#
echo "" >> $logfile
echo "# Finished:      `date`"                          >> $logfile
echo "" >> $logfile

####################################################################

if ("$prjdir" == "yes") then
   # drive the merge process from the convert logfile
   cat $logfile | grep -v '#' | grep '^.' > $mergelist
   # need to place _msg files too
   cat $logfile | grep '# Read' | awk '{print $5}' > $msglist

   set num_lines="`cat $msglist | wc -l | tr -d ' '`"
   set curline=1
   while ($curline <= $num_lines)
      set raw=`sed -n "$curline p" $msglist`
      @ curline++
      set convdir="$raw:h"
      set delta=`echo "$startdir $convdir" | awk '{s=$1; c=$2; print substr(c,length(s)+2)}'`
      cp $raw $sv_startdir/$delta
   end

   set num_lines="`cat $mergelist | wc -l | tr -d ' '`"
   set curline=1
   while ($curline <= $num_lines)
      set raw=`sed -n "$curline p" $mergelist`
      @ curline++
      set strtfullfilev=`echo "$raw" | awk '{print $1}'`
      set strtdir="$strtfullfilev:h"
      set convfullfilev=`echo "$raw" | awk '{print $2}'`
      set convfilev="$convfullfilev:t"
      set convdir="$convfullfilev:h"
      set convext=`echo $convfilev | awk -F. '{print $2}'`
      set convver=`echo $convfilev | awk -F. '{print $3}'`
      set convnameonly=`echo $convfilev | awk -F. '{print $1}'`
      set convfile="${convnameonly}.${convext}"

      # get delta of $targetdir, $convdir
      set delta=`echo "$targetdir $convdir" | awk '{s=$1; c=$2; print substr(c,length(s)+2)}'`
      set delta_sl="/$delta"
      if ("$delta" != "") then
         set destdir="$sv_targetdir/$delta"
      else
         set destdir="$sv_targetdir"
      endif
      # make sure destdir exists
      set build="$sv_targetdir"
      set numdirs=`echo $delta | tr '/' ' ' | wc -w`
      set i=1
      while ("$i" <= "$numdirs")
         set newdir=`echo $delta | awk -F/ '{print $'$i'}'`
         @ i++
         set build="$build/$newdir"
         if (! -d $build) mkdir $build
      end 

      set nonomatch
      set exist=`$ls_cmd $startdir$delta_sl/$convfile.* |& tail -1` 
      unset nonomatch
      set conv_v=`$ls_cmd $startdir$delta_sl/$convfile.* |& egrep '[a-z]*.[a-z]*[0-9]?$' | sort -t. +2n | tail -1 | awk -F. '{print $3}'` 

      set dest_v="1"
      if ("$sv_startdir" == "$sv_targetdir") set dest_v="$conv_v"

      cd $strtdir
      set nonomatch
      # next wildcard should only find one instance, tail just in case
      set headfile=`$ls_cmd ${convfile}*_h | tail -1`
      unset nonomatch
      # should never happen 
      if (`echo "$headfile" | grep "$nonoline" | wc -c` > 0) then
         echo "# INFO:  can't find _h file for $convfullfilev" >> $logfile
      endif
      # Prepare names for join
      # move in same partition
      set convtmp="$convdir/${convfile}.${dest_v}_b"
      mv -f $convfullfilev $convtmp
      # copy since maybe diff part
      set headtmp="$convdir/${convfile}.${dest_v}_h"
      cp $strtdir/$headfile $headtmp
      
      # RUN PRJUTIL - JOIN
      cd $convdir
      if (`grep "^$dumheadstr" $headtmp | wc -l` != 0) then
         cp $convtmp $destdir/$convfile.$dest_v
         set prjutil_status="$prjutil_good"
      else
         $prjutil join $convfile.$dest_v $destdir >& /dev/null
         set prjutil_status="$status"
      endif
      switch ($prjutil_status)
         case $prjutil_noaction
            # nothing to do - join shouldn't give this, actually
         breaksw

         case $prjutil_good
            # nothing to do
         breaksw

         case $prjutil_bad
            echo "# ERROR:  $name internal error (prj header insertion failed)." >> $logfile
         breaksw

         default
            echo "# ERROR:  undef status on '$prjutil join'" >> $logfile
         breaksw
      endsw

      if ("$purgefiles" == "yes") then
         cd $destdir
         purge $convfile
      endif
   end

   # Fix the log file.
   mv -f $logfile $logfile.old
   cat $logfile.old | sed s+$startdir+$sv_startdir+ | sed s+$targetdir+$sv_targetdir+ > ${logfile}
   rm -f $logfile.old
endif

####################################################################


#                            FINISHED
QUICK_EXIT:
cd $initialdir
rm -rf $tmpdir
exit 0



########################################################################
#
#                  INFORMATION ABOUT THIS SCRIPT
#
########################################################################

USAGE:
set usage1="Usage:  $name pro_command [-help] [-ok] [-s src_dir] [-l filename] [-r]"
set usage2="        [-t target_dir] [-geom] [-k mins] [-tmp dir] [-ms Kb] [-c configfile]"
if ($?import_mode) then 
   set usage3="        [-ie extension] -if prt|drw"
   set mode_descrip="Converts iges files into Pro/ENGINEER parts or drawings."
else if ($?cvt8_mode) then
   set usage1="Usage:  $name pro_command [-help] [-ok] [-prj_conv prjname] [-tmp dir]"
   set usage2=""
   set usage3=""
   set mode_descrip="Converts old projects into Pro/ENGINEER Release 8.0 format."
else
   set usage3="        [-p] [-f] [-prjdir dir] [-prj_name prjname] [-prj_conv prjname]"
   set mode_descrip="Converts Pro/ENGINEER files between short and long term."
endif
echo ""
echo "$usage1"
if ("$usage2" != "") echo "$usage2"
if ("$usage3" != "") echo "$usage3"
echo ""
echo "        $mode_descrip"
echo ""
echo "OPTIONS"
echo ""
echo "  -help     Display this information."
echo ""
echo "  -ok       Confirms that you are satisfied with the backup of the files"
echo "            to be converted."
echo "            Default:  If flag is not present you will be prompted for an answer."
echo ""
echo "  -tmp      Temporary dir for $name's use.  The dir's partition must"
echo "            have at least enough space for storage of the largest file to be"
echo "            converted."
echo "            Default:  /tmp"
if ($?import_mode) then
echo ""
echo "  -if       Import format - indicates whether to read iges file information"
echo "            as a Pro/ENGINEER part or drawing."
echo "            Default:  none - you must specify one of:  drw prt"
echo ""
echo "  -ie       Indicates the iges file extension."
echo "            Default:  igs"
#echo ""
#echo "  -ps       Indicates paper size to use when importing an iges drawing."
#echo "            Default:  none - must specify one of:  a b c d e f a[0-4]"
endif
if ($?import_mode || $?full_mode) then
echo ""
echo "  -s        Name of a directory containing files to convert (the start"
echo "            directory)."
echo "            Default:  the current directory."
echo ""
echo "  -l        Name of a file containing a list of filenames to convert."
echo "            Filenames (ex: box.prt) should be listed one per line."
echo "            Do not specify a versions, the latest files will be converted."
echo "            Default:  convert all the files in the start directory." 
echo ""
echo "  -r        Recursively convert files in dirs encountered below startdir."
echo "            Default:  convert only the files in the start directory."
echo ""
echo "  -t        Name of a directory in which to write converted files."
echo "            Default:  the start directory."
echo ""
echo "  -geom     Store geometry when converting."
echo "            Default:  no geometry is stored."
echo ""
echo "  -k        The maximum length of time (in minutes) allowed for the conversion."
echo "            of a file.  After this time the process converting the current"
echo "            file is killed."
echo "            Default:  0  (0 = no limit)."
echo ""
echo "  -ms       The minimum amount of disk space (Kb) required to do conversions."
echo "            This is checked after each conversion and $name aborts if"
echo "            there is not enough space."
echo "            Default:  0  (0 = no limit)."
echo ""
echo "  -c        EITHER - Name of a config. file to use before each conversion"
echo "            OR - 'existing' means to use the conversion dir's config.pro"
echo "            if present."
echo "            OR - 'none' means not to use a config. file, even if"
echo "            config.pro is present in a conversion dir."
echo "            Default:  'existing'"
endif
if ($?full_mode) then
echo ""
echo "  -p        Purge each file after conversion."
echo "            Default:  do not purge after conversion."
echo ""
echo "  -f        Force conversion of all files."
echo "            Default:  Don't convert files which are already long term."
echo ""
echo "  -prjdir   Indicates that the dirs for conversion have been created with"
echo "            Pro/PROJECT"
echo "            Default:  Only convert non Pro/PROJECT dirs."
echo ""
echo "  -prj_name Pro/PROJECT project name - all files in the project will be"
echo "            converted"
endif
if ($?full_mode || $?cvt8_mode) then
echo ""
echo "  -prj_conv Indicates the name of a project to convert to Release 8.0 format."
endif
if ($?full_mode) then
echo ""
echo "NOTES"
echo ""
echo "  1.  -prjdir and -prj_name are mutually exclusive and Pro/ENGINEER dependant"
echo "      the former is valid with Pro/ENGINEER 5.0, the latter with 6.0+"
echo ""
echo "  2.  -prjdir will convert non-project files, but a space overhead is involved"
echo "      It is most efficient to use -prjdir on ONLY project directories."
echo ""
echo "  3.  -s, -t, -p, -r are not applicable with -prj_name."
echo ""
echo "  4.  -tmp is the only applicable option with -prj_conv."
endif
echo ""
echo ""
echo "EXAMPLES"
echo ""
if ($?import_mode) then
echo "$name pro -if drw -ok            - Convert all .igs files in this dir"
echo "                                        to Pro/ENGINEER drawings."
echo "$name pro -if prt -r -ok         - Convert all .igs files in this tree"
echo "                                        to Pro/ENGINEER parts."
else if ($?cvt8_mode) then
echo "$name pro -prj_conv proj1 -ok    - Convert project proj1 to 8.0 format."
else
echo "$name pro -ok                    - Convert all files in this dir."
echo "$name pro -ok -r                 - Convert all files in this tree."
echo "$name pro -ok -l files.txt -geom - Convert files in files.txt with"
echo "                                          geometry."
endif
echo ""
exit 1




########################################################################
#                                                                      #
#                     MACHINE CONFIGURATION                            #
#                                                                      #
# input parameter 'mc_type'  - must be set, possibly ""                #
########################################################################
MACHINE_CONFIG:

set supported_mc = ("sun4" "apollo" "sgi" "decstation" "hp300" "ibm_rs6000" "dg" "hp700" "hp8k" "hpux11_pa32" "hpux_pa64" "nec_risc" "mips_risc" "sgi_r4k" "alpha_unix" "sun4_solaris" "sun4_solaris_64" "hitachi" "sgi_elf2" "sgi_mips4")

unset valid
while (! $?valid)
   set i=1
   while ($i <= $#supported_mc && ! $?valid)
      if ("$mc_type" == "$supported_mc[$i]") set valid
      @ i++  
   end

   if (! $?valid) then
      if ("$mc_type" != "") echo "ERROR: '$mc_type' is not a valid machine"
      echo ""
      set def_mc=""
   endif

   if (! $?valid) then
      echo ""
      echo "                      Supported machine types are:"
      echo ""
      echo "$supported_mc"
      echo ""
      echo -n "                      Machine type $def_mc ?: "
      set mc_type="$<"
      echo ""
      echo ""
   endif
end

#
# COMMON VALUES (MAY BE MODIFIED)
#
set df_cmd="/bin/df"
set unixflavor="sys5"
set nonoline="not found"
set whichline_tmp="no __CMD__ in"
set gfxnum="0"
set rsh_cmd="rsh"

switch ($mc_type)
   case sun3
   case sun386
   case sun4
   case sun4_solaris
   case sun4_solaris_64
      set path=(/usr/ucb $path)  # ensures BSD ps/df/du etc on Solaris.
      if ("$mc_type" == "sun4_solaris") then
           set df_cmd = "/bin/df -k"  # make it work for solaris 2.4
      endif
      set mcol="6"
      set fcol="4"
      set dfunits="Kb"
      set unixflavor="bsd"
      if ("$mc_type" == "sun4_solaris") set nonoline="No such file or directory"
   breaksw

   case apollo
      set mcol="6"
      set fcol="4"
      set dfunits="Kb"
      set unixflavor="bsd"
   breaksw

   case sgi
   case sgi_elf2
   case sgi_r4k
   case sgi_mips4
      #set gfxnum="7" # this will be put to 0 later in script if poss.
      set mcol="7"
      set fcol="5"
      set dfunits="blocks"
      set nonoline="No such file or directory"
      set rsh_cmd="/usr/bsd/rsh"
   breaksw
		 
   case nec_risc
      set mcol="1"
      set fcol="3"
      set dfunits="blocks"
      set rsh_cmd="remsh"
   breaksw

   case mips_risc
      set mcol="7"
      set fcol="5"
      set dfunits="blocks"
      set nonoline="No such file or directory"
   breaksw

   case decstation
      set mcol="6"
      set fcol="4"
      set dfunits="Kb"
      set unixflavor="bsd"
      set nonoline="No such file or directory"
   breaksw

   case hp300
      set mcol="6"
      set fcol="4"
      set df_cmd="bdf"
      set dfunits="Kb"
      set rsh_cmd="remsh"
   breaksw

   case ibm_rs6000
      set mcol="7"
      set fcol="3"
      set dfunits="Kb"
      set nonoline=" not "  # does not exist &  not found combo
   breaksw

   case hp800
      set mcol="1"
      set fcol="3"
      set dfunits="blocks"
   breaksw

   case hp700
   case hp8k
   case hpux11_pa32
   case hpux_pa64
      set mcol="6"
      set fcol="4"
      set df_cmd="bdf"
      set dfunits="Kb"
      set rsh_cmd="remsh"
   breaksw

   case dg
      set mcol="1"
      set fcol="3"
      set dfunits="blocks"
      set nonoline="No such file or directory"
      set rsh_cmd="remsh"
   breaksw

   case alpha_unix
      set mcol="6"
      set fcol="4"
      set df_cmd="df -k"
      set dfunits="Kb"
      set rsh_cmd="remsh"
   breaksw

   case hitachi
      set mcol="6"
      set fcol="4"
      set df_cmd="bdf"
      set dfunits="Kb"
      set rsh_cmd="remsh"
   breaksw
endsw


if ("$mc_type" == "alpha_unix") then
   set ps_cmd="ps -o pid,ppid,comm"
   set pidcol="1"
   set ppidcol="2"
   set cmdcol="3"
else if ("$unixflavor" == "bsd") then
   set ps_cmd="/bin/ps -lw"
   set pidcol="3"
   set ppidcol="4"
   set cmdcol="14"
else
   set ps_cmd="/bin/ps -ef"
   set pidcol="2"
   set ppidcol="3"
   set cmdcol="8"
endif
 

ls -1 >& /dev/null
if (! $status) then
   set ls_cmd="/bin/ls -1"
else
   set ls_cmd="/bin/ls"
endif

set which_ret=`which which |& tee`
if (`echo "$which_ret" | grep "Command not found" | wc -l` == 0) then
   set use_which
else
   unset use_which
endif

goto MACHINE_CONFIG_DONE
