#! /bin/sh

# converts a matrix to a feature list
# copyright Hans Paijmans 1995,1996
# ========================================
# 13 dec. 1995 change: option -l added 
# ========================================

naam="$1"
laatste=0

if [ -z $naam ] ; then 
   naam="-h"; 
fi

if [ $naam = '-h' ] ; then
   echo "Usage : de-matrix [-options] filename"
   echo "        filename : matrixfile in the format"
   echo "                   row_feature w_col_1 w_col_2 ... w_col_n"
   echo "        -h       : this message"
   echo "        -f       : full (include empty cells)"
   echo "Output: featurelist in the format"
   echo "        col_1 row_feature weight"
   echo "Copyright Hans Paijmans 1995"
   exit 1
fi

set -- `getopt hf $*`

for i do
      case "$i" in
        -h)
           help=1; shift;;
        -f)
           full=1; shift;;
        --)
           shift; break;;
       esac
done

naam=$1;


awk '
   BEGIN {
       for (n=1;n<1000;n++) column[n]=n;
       x=1;y=1;
       files=1}

{

  if ((length($0)>3) && (substr($0,1,1)!="#"))
     {
     if ($1=="!") for (n=2; n<NF+1;n++) column[x++]=$n;
     else
       {

       for (n=2; n<NF+1; n++)
              if (f) printf("%s %s %s\n", column[n-1], $1, $n);
              else  if ($n!="0") printf("%s %s %s\n", column[n-1], $1, $n);
       }
     }
}

END { 

    }
' f=$full $naam


