package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/google/pprof/profile"
)

func main() {
	p, err := profile.Parse(os.Stdin)
	if err != nil {
		fmt.Fprintf(os.Stderr, "input: %v", err)
		os.Exit(1)
	}

	for _, s := range p.Sample {
		var fns []string
		if len(s.Value) < 1 {
			continue
		}
		for i := len(s.Location) - 1; i >= 0; i-- {
			l := s.Location[i]

			// Location ID 0 is invalid in the protobuf format, so 1 is the
			// first valid ID. The slice, however, is zero-indexed.
			id := int(l.ID - 1)
			if id < 0 || id >= len(p.Location) {
				break
			}

			lines := p.Location[id].Line
			if len(lines) < 1 {
				continue
			}
			if lines[0].Function == nil {
				continue
			}
			name := lines[0].Function.Name
			if strings.ContainsAny(name, " ;") {
				continue
			}
			fns = append(fns, lines[0].Function.Name)
		}
		fmt.Printf("%s %d\n", strings.Join(fns, ";"), s.Value[0])
	}
}
