#!/bin/csh

foreach file ( OUTCAR.static OUTCAR OUTCAR.relax )
  if ( -e $file ) then
    set mycatfile="cat $file"
  endif
  if ( -e ${file}.gz ) then
    set mycatfile="zcat ${file}.gz"
  endif
end


$mycatfile | getlines -bt 'absolut eigen' '-----' | grep -v '\-\-\-' | tail -n +3 |\
awk '{x=$4; y=$5; z=$6; getline;\
if ($1!="") {\
  cb=""; vb="";\
  while (1) {\
    getline;\
    if ($1=="") break;\
    if ($3>0.5) {vb=$2;}\
    if ($3<0.5 && cb=="") {cb=$2;}\
  }\
  print x,y,z,vb,cb;\
}\
}' >! allk.tmp

if ( x$1 == "x-k" ) then
  cat allk.tmp
else
  grep -v '^ *$' allk.tmp | awk 'BEGIN {vb=-10000; cb=10000} {vb=($4>vb ? $4 : vb); cb=($5<cb ? $5 : cb)} END {gap=cb-vb; if (gap<0) {gap=0;} print gap}'
endif
