#!/bin/bash

#
# Copyright (C) 2006,2007 Luotao Fu, Pengutronix (lfu@pengutronix.de)
#
# parse the output file of cyclictest in debug mode in plottable histogramm
# files, single files are automatically created on detecting new threads.
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License version 2 as
#  published by the Free Software Foundation;
#
#  Software distributed under the License is distributed on an "AS
#  IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
#  implied. See the License for the specific language governing
#  rights and limitations under the License.

set -e

args=$(getopt i: $*)

if [ $? -ne 0 ] || [ $# -eq 0 ];then
    echo "Usage: $(basename $0) -i inputfile"
    exit 1
fi
for i in $args; do
    case "$i" in
	-i) shift;logfile_name=$(basename $1);;
    esac
done

logfile_name_prefix=$(echo $logfile_name | cut -d . -f 1)
step_dist=2
thread_sum=0
step_counter=0

IFS_BUF=$IFS
IFS="$IFS:"

echo -n "splitting single thread logs"


while read thread_nr loop_count m_result ;do 
    echo "${loop_count} ${m_result}" >> ${logfile_name_prefix}_plot_thread${thread_nr}".log"
    #determine thread summary and search for min, max
    if [ ${loop_count} -eq 0 ];then
	if [ ! $thread_nr ] || [ ! $loop_count ] || [ ! $m_result ];then
	    echo "parsing failed, check your input file"
	    exit 1
	fi
	(( thread_sum++ ))
	if [ -e ${logfile_name_prefix}_plot_thread${thread_nr}".log" ] ; then
	    rm ${logfile_name_prefix}_plot_thread${thread_nr}".log"
	fi
    elif [ $loop_count -eq 1 ];then
	max[thread_nr]=${m_result}
	min[thread_nr]=${m_result}
    else
	if [ ${m_result} -gt ${max[thread_nr]} ];then
	    max[thread_nr]=${m_result}
	elif [ ${m_result} -lt ${min[thread_nr]} ];then
	    min[thread_nr]=${m_result}
	fi
    fi

    #now try to collect histogram data
    if [ $loop_count -ne 0 ];then
	hist_index=$(( ${m_result}/${step_dist} ))
	tmp_name=hist_data_${thread_nr}[$hist_index]
	tmp_val=${!tmp_name}
	(( tmp_val++ ))
	eval ${tmp_name}=${tmp_val}
    fi

    #we'd give the user some lifesign every 5000 lines
    if [ $(( ${loop_count} / 5000 )) -ge $step_counter ]; then
	echo -n "."
	(( step_counter++ ))
    fi
done < $1
echo done

echo -n "making histogram files"


for ((thr_co=0; thr_co < thread_sum ; thr_co++)); do
    echo -n "."
    hist_array=hist_data_${thr_co}[@]
    hist_index=0;
    if [ -e ${logfile_name_prefix}_hist_thread${thr_co}".log" ]; then
	rm ${logfile_name_prefix}_hist_thread${thr_co}".log"
    fi
    hist_index_max=$(( ${max[$thr_co]}/${step_dist} ))

    for ((i=0; i < ${hist_index_max} ; i++)); do
	var_pnt=hist_data_${thr_co}[${i}]
	index_value=$((${i} * ${step_dist} + ${min[${thr_co}]}))
	if [ ! -z ${!var_pnt} ]; then
		echo "$index_value ${!var_pnt}" >> ${logfile_name_prefix}_hist_thread${thr_co}".log"
	fi
	done
done


echo done

IFS=$IFS_BUF
