#!/bin/csh 

# join two logo files to show one beneath the other

# Checking input argument

# How many arguments passed to the shell ?
  set arguments = `echo $* | wc -w`

  if ($arguments != 3) then
     echo "$0 fname_logo1.ps  fname_logo2.ps offset"
     echo "This shell needs the file names of two logo files and the offset of their alignment"
     echo "The second logo will be moved forward, so that the offset must be positive."
     echo "You may have to switch the order of the logo files to achieve this."
     exit
  endif

# Are the first two arguments files with data 
  if (!(-e $1) || -z $1) then
     echo "First argument ($1) is not an existing file with data !"
     exit
  endif

  if (!(-e $2) || -z $2) then
     echo "Second argument ($2) is not an existing file with data !"
     exit
  endif


# checking if the third argument is a (reasonable) positive integer.
  if (`echo $3 | sed 's/^[0-9][0-9]*$/+int/'` != "+int") then
     echo "Third argument (logos offset) doesn't look like a positive integer !"
     echo "The second logo will be moved forward, realtive to the first, so that the offset must be positive."
     echo "You may have to switch the order of the logo files to achieve this."
     exit
  endif
  if ($3 > 1000) then
     echo "Logos offset ($3) seems too big."
     exit
  endif


# find the line number of the end of the logo-caption lines in the first file
  @ endcaption1 = (6 + `grep -n create $1 | grep -v "{" | awk '-F:' '{print $1}'`)
# copy first file up to end of logo caption
  head -$endcaption1 $1 

# increment by one the line number so that the rest of the file would be copied later
  @ endcaption1 = ($endcaption1 + 1)


# write a 'translate' command to precede the second logo caption
  echo '     0 -1 linemove barheight mul mul translate' 


# find the line number of the end of the logo-caption lines in the second file
  @ endcaption2 = (6 + `grep -n create $2 | grep -v "{" | awk '-F:' '{print $1}'`)
# copy second caption
  head -$endcaption2 $2 | tail -4 


# find the line number of the end of the logo lines in the first file
  set endlogo = `grep -n endline $1 | grep -v "{" | awk '-F:' '{print $1}'`

# write first logo file from the end of the caption up to the end of the logo
  head -$endlogo $1 | tail +$endcaption1 


# find the line numbers of the start and end of the logo lines in the second file
  set startlogo = `grep -n startline $2 | grep -v "{" | awk '-F:' '{print $1}'`
  @ startlogo = ($startlogo + 1)
  set endlogo = `grep -n endline $2 | grep -v "{" | awk '-F:' '{print $1}'`


# write "startline" command
  echo "startline % line number 2"


# create logos offset by adding "shift" commands to file
  set index = $3 
  while ($index > 0)
     @ index = ($index - 1)
     echo "shift" 
  end


# write second logo lines
 head -$endlogo $2 | tail +$startlogo 


# write "endpage" command 
  echo "endpage" 

 exit
