#! /bin/sh
DOF_FREE_SIZE=$1
MAX_STRIDE=$2
FW=$(( ${DOF_FREE_SIZE} / 4 ))
PRINT="printf"
#echo -n -e

ALLBITS=$(( (1 << ${DOF_FREE_SIZE}) - 1 ))
if test ${ALLBITS} -eq 0; then
    ALLBITS=$(( ~0 ))
fi
WRAP=$(( (80-4) / (${FW} + 4) )) 

if test ${MAX_STRIDE} -gt 1; then
    cat <<EOF
/* automatically generated by configure, do not edit */
#ifndef _ALBERTA_STRIDE_DOF_FREE_BIT_H_
#define _ALBERTA_STRIDE_DOF_FREE_BIT_H_
EOF
    ${PRINT} '\n#define MAX_STRIDE '"${MAX_STRIDE}"'\n\n'
    cat <<EOF
const DOF_FREE_UNIT dof_stride_free_bit[MAX_STRIDE][DOF_FREE_SIZE] = {
EOF
else
    cat <<EOF
/* automatically generated by configure, do not edit */
#ifndef _ALBERTA_DOF_FREE_BIT_H_
#define _ALBERTA_DOF_FREE_BIT_H_
const DOF_FREE_UNIT dof_free_bit[DOF_FREE_SIZE] = {
EOF
fi

STRIDE=1
while test ${STRIDE} -le ${MAX_STRIDE}; do
    MASK=0
    BIT=0
    while test ${BIT} -lt ${STRIDE}; do
	MASK=$(( ${MASK} | (1 << ${BIT}) ))
	BIT=$(( ${BIT} + 1 ))
    done
    BIT=0

    if test ${MAX_STRIDE} -gt 1; then
	${PRINT} '  {\n    '
    else
	${PRINT} '  '
    fi
    while test ${BIT} -lt ${DOF_FREE_SIZE}; do
	VALUE=$(( (${MASK} << ${BIT}) & ${ALLBITS} ))
	${PRINT} '0x%0'${FW}'x' ${VALUE}
	BIT=$(( ${BIT} + 1 ))
	if test ${BIT} -lt $(( ${DOF_FREE_SIZE} + ${MAX_STRIDE} - 1 )); then
	    if test $(( ${BIT} % ${WRAP} )) -eq 0; then
		if test ${MAX_STRIDE} -gt 1; then
		    ${PRINT} ',\n    '
		else
		    ${PRINT} ',\n  '
		fi
	    else
		${PRINT} ', '
	    fi
	fi
    done
    if test ${MAX_STRIDE} -gt 1; then
	${PRINT} '\n  }'
    fi
    if test ${STRIDE} -lt ${MAX_STRIDE}; then
	${PRINT} ',\n'
    else
	${PRINT} '\n'
    fi
    STRIDE=$(( ${STRIDE} + 1 ))
done

if test ${MAX_STRIDE} -gt 1; then
    cat <<EOF
};
#endif /* _ALBERTA_DOF_STRIDE_FREE_BIT_H_ */
EOF
else
    cat <<EOF
};
#endif /* _ALBERTA_DOF_FREE_BIT_H_ */
EOF
fi

