#!/bin/csh -f

# Test to see if we're running on windows NT
set CPIO = cpio
if ( $?OS ) then
    if ( $OS == Windows_NT || $OS == linux ) set CPIO = hcpio
endif
if ( $?OSTYPE ) then
    if ( $OSTYPE == Windows_NT || $OSTYPE == linux ) set CPIO = hcpio
endif

@ errorflag  = 0
@ prefixflag = 0

if ($#argv > 2 || $#argv < 1) then
    @ errorflag = 1
else if ($#argv == 2) then
    if ("$argv[1]" != "-p") @ errorflag = 1
    @ prefixflag = 1
    set file = $argv[2]
else if ("$1" == "-") then
    @ errorflag = 1
else if ( ! -f $1 ) then
    echo file $1 not found
    @ errorflag = 1
else
    set file = $argv[1]
endif

set filebasename = `basename $file`


if ($errorflag == 1) then
    echo "usage: hexpand [-p] <hip_file>"
    echo "       -p: prepends the 'cpio.' prefix to the contents and dir files"
    echo
    echo "hexpand will expand a Houdini .hip file into a directory structure"
    echo "that can be browsed and edited using standard tools, then collapsed"
    echo "back into a regular .hip file using hcollapse"
    exit
endif

if ($prefixflag == 1) then
    set prefx = cpio.
else
    set prefx = ""
endif

if ( -d ${prefx}${filebasename}.dir ) then
    echo directory ${prefx}${filebasename}.dir already exists.
    echo remove it before continuing.
    exit
endif

mkdir ${prefx}${filebasename}.dir
$CPIO -itI ${file} > ${prefx}${filebasename}.contents
if ! $status then 
    echo table of contents for $file stored in ${prefx}${filebasename}.contents
    cd ${prefx}${filebasename}.dir
    $CPIO -idI ../${file}
    echo ${file} expanded into the directory ${prefx}${filebasename}.dir
else
    echo ${filebasename} does not seem to be a .hip file.
    # Clean up the dirt we created.  The directory should be empty
    # so a mere rmdir should work.
    rm -f ${filebasename}.contents
    rmdir ${filebasename}.dir
endif
cd ..
