#! /usr/bin/perl

$cpath=`pwd`;
chomp($cpath);
if ($cpath =~ m|/opc(-[\d.]+)?$|) {
    $err_h="./libopc/include/opclib_module.h";
    $error_h="./libopc/opcmodule.c";
} elsif ($cpath =~ m|libopc(-[\d.]+)?$|) {
    $err_h="./include/opclib_module.h";
    $error_h="./opcmodule.c";
} elsif ($cpath =~ m|libopc(-[\d.]+)?/tools$|) {
    $err_h="../include/opclib_module.h";
    $error_h="./opcmodule.c";
} else {
    $path="."; $exitflag = 1;
    while ($exitflag) {
	$path = $path . "/..";
    	@files = glob($path . "/libopc*");
	for $file(@files) {
	    if (-d $file) {
		$path=$file;
		$exitflag = 0;
		last;
	    }
	}
    }
    $err_h="$path/include/opclib_module.h";
    $error_h="$path/opcmodule.c";
}

open INPUT, $error_h;
@OLD = <INPUT>;
close INPUT;

open OUTPUT, ">$error_h";
foreach $line(@OLD) {
    if ($flag) {
	if ($line =~ m/}\s*;/) {
	    $flag=0;
	    print OUTPUT $line;
	    print OUTPUT "#define opc_modules_number $number\n";
	} 
    } else {
        if ($line =~ m/#define\s+opc_modules_number/) {
	    ;
	} else {
	    print OUTPUT $line;
	}
	if ($line =~ m/static\s+DSModuleNameS\s+opc_module_names\[\]\s*=\s*{/) {
	    $flag=1;
	    
	    open INPUT, $err_h;
	    $number = 0; $skip_flag = 0;
	    while (<INPUT>) {
		if ($_ =~ m/\/\*/) { $skip_flag = 1; }
		if ($_ =~ m/\*\//) { $skip_flag = 0; }
		elsif ($skip_flag) { next; }
		
		if ($_ =~ m/^\s\/\//) { next; }
		if ($_ =~ m/OPC_MODULE_USED_BY/) { next; }
		
		if ($_ =~ m/^#define\s*(OPC_MODULE_(\w+))\s+([\dxABCDEFabcdef]+)/) {
		    $name = $2; $id = $3;
#		    $name =~ s/(\w)([A-Z])/\1_\2/g;
#		    $name = uc($name);
		    
		    if ($number++) {
			print OUTPUT ",\n";
		    } 
		    print OUTPUT "\t{$id, \"opc$name\"}";
		}
	    }
	    print OUTPUT "\n";
	    close INPUT;
	}
    }
}
close OUTPUT;
