import sys
import re
import csv

def parse_res_file(filename):
    # Extract A value from filename
    a_match = re.search(r'template_A_(-?[\d.]+)\.res$', filename)
    if not a_match:
        raise ValueError(f"Invalid filename format: {filename}")
    a_value = float(a_match.group(1))
    
    # Regex pattern for matching the lines
    pattern = re.compile(r'.*in\s+\[([\d.]+),\s*([\d.]+)\]\s+\(([\d.]+)%\s+CI\)$')
    
    with open(filename, 'r') as f:
        matches = []
        for line in f:
            match = pattern.search(line.strip())
            if match:
                lb = float(match.group(1))
                ub = float(match.group(2))
                ci = float(match.group(3))
                matches.append((lb, ub, ci))
                
        #if len(matches) != 3:
        #    raise ValueError(f"Expected 3 matches in {filename}, found {len(matches)}")
            
    return a_value, matches

def main():
    if len(sys.argv) < 2:
        print("Usage: python res_parser.py <res_files...>", file=sys.stderr)
        sys.exit(1)
    
    writer = csv.writer(sys.stdout)
    writer.writerow([
        'A', 'd01_lb', 'd01_ub', 'd01_ci',
        'd12_lb', 'd12_ub', 'd12_ci',
        'd23_lb', 'd23_ub', 'd23_ci'
    ])
    
    for filename in sys.argv[1:]:
        try:
            a_value, matches = parse_res_file(filename)
            row = [a_value, matches[0][0], matches[0][1], (matches[0][1]+matches[0][0])/2]
            #for lb, ub, ci in matches:
            #    row.extend([lb, ub, ci])
            writer.writerow(row)
        except Exception as e:
            print(f"Error processing {filename}: {str(e)}", file=sys.stderr)

if __name__ == "__main__":
    main()
