# Copyright 1999 Earthstar Geographics (www.es-geo.com).
#
# Converts an 8-bit, single band ER Mapper dataset to a
# a classified image. This is designed for using classifcations
# created in another product and imported into ER Mapper as
# a binary file. The wizard does the following:
#
#	1) Asks for the input file (must be ERS format)
#	2) Determines the data range (number of classes)
#	3) Renames the original ERS header to "xxx.ers.orig"
#	   (so you can revert back to it if desired).
#	4) Builds a new 'classified' ERS header file with
#	   original's metadata and a graduated greyscale
#	   color scheme for the image.
#
# After conversion, the dataset can be treated like a
# classified image created in ER Mapper, i.e., you can
# change class colors and names using 
# Edit/Edit Class Region/Color, etc or build a legend
# in map composition.
#
# IMPORTANT: Stats can only be calculated for pixel counts
# and areas because there is no "source" dataset for ersstats
# to pull the multispectral values from. 

$erm_machine_type = getenv "ERM_MACHINE_TYPE"

if($erm_machine_type == "win32") then goto use_pc_cmd
	$ls_cmd = "ls "
	$dir_sep = "/"
	$type_cmd = "more "
	$copy_cmd = "cp "
	goto setup_defaults

use_pc_cmd:
	$cmd_processor = getenv "ComSpec"
	$ls_cmd = $cmd_processor + " /c dir /b /ON "
	$type_cmd = $cmd_processor + " /c type "
	$copy_cmd = $cmd_processor + " /c copy "
	$dir_sep = "\\"

setup_defaults:
$show_image = 1
$calc_stats = 1
$curr_col = 0

# Let's go.

wizard_page1:
wizard begin "Create Classified Image Wizard"
	title  "Convert to Classified Image Wizard"
	container begin "data_entry1" 
		labels_left
		say "Use this wizard to convert a single band, 8-bit"
		say "ER Mapper dataset to a 'classified' dataset."
		say "This lets you work with a classified image"
		say "created in a different product."
		say ""
		ask file "Input image:" ".ers" $bil_dataset
		say ""
		ask yesno "Calculate stats on class pixel counts" $calc_stats
		ask yesno "Display classified image at end" $show_image
		say ""
		say "Note: This wizard does not perform a"
		say "classification - use ER Mapper to do that."
	container end

	container begin "page_controls"
		height_pct 12
		below "data_entry1"
		horizontal right justify
		ask action "Help" goto help_page1
		ask action "Finish" goto page1_validate
		ask action "Cancel" close goto wizard_cancel
	container end

container begin "Image"
container width_pixels 120
container height_pixels 280
container left "data_entry1"
container above "page_controls"
show image "standard_icons/Wizards/esg-cvtclas"
container end

wizard end

	help_page1:
	say warning "This wizard converts a single band, 8-bit ER Mapper dataset into what ER Mapper considers to be a 'classified' image. This lets you treat a classified image created in another product as a classified image in ER Mapper. After conversion, you can:\n \n- choose class colors and names\n- create a classification legend\n- assign specific colors to specific pixel values.\n \nClick OK to view help page 2."
	help_page2:
	say warning "The wizard creates a new 'classification' version of the ERS header file (it does not write a new data file). The original ERS file is copied to a backup (.bak) so you can revert to it if desired.\n \nNote: Statistics are only for class pixel counts, areas, etc. Since there is no 'source' multispectral dataset, those statistics cannot be calculated.\n \n(Version 1.0. Earthstar Geographics, 1999.)"
	goto wizard_page1

page1_validate:
	check_dataset:
	if ($bil_dataset != "") then goto check_image_type
	say warning "Please specify an input image to be converted to a classified image." 
	goto wizard_page1

check_image_type:
	new algorithm
	set layer dataset to $bil_dataset
	$bil_celltype = get layer cell type

if ($bil_celltype != uint8) then goto error_celltype

	$bil_bands = get layer band count

if ($bil_bands > 1) then goto error_to_many_bands

	goto get_data_limits

error_celltype:
	say warning "Your input dataset must be in unsigned 8-bit integer format. Please specify a different dataset."
	goto wizard_page1

error_to_many_bands:
	say warning "Your input dataset has more than one band. Please specify a dataset with only one band."
	goto wizard_page1

get_data_limits:

wizard close

open status "Convert to Classified Image Status"
say status "\n"
say status "\n"

# First add the 'process at dataset resolution' filter so we
# can get the true data range.

first raster layer
	add convolution filter
	set filter rows to 1
	set filter cols to 1
	set filter matrix 1 1 1
	set filter postsampled false

# Now get the actual data range, which gives the number of
# classes we end up with.

say status "determining number of classes, please wait...\n"
	go algorithm
	first pseudo layer
	last transform
	set transform limits to actual

	$lowval = get transform input min
	$highval = get transform input max

say status "class range found = " + $lowval + " to " + $highval + "\n"

parse_orig_ers_file:
	$cmd = $type_cmd + $bil_dataset
	system $cmd
	$billines = split $SYS_STDOUT at "\n"
		$line = 1
	
	get_header_lines:
#	say status $billines[$line] + "\n"
	if ($billines[$line] == "		BandId Begin") then goto done_header
	$line = $line + 1
  	goto get_header_lines
 
	done_header:
	$total_lines = $line

# Find the lines with number of rows and columns and get those
# values (used for the 'All' polygon region size block).

find_rows_and_cols:
	$line = 1
	
	flag_nroflines:
	$fields = split $billines[$line] at " "
	if ($fields[1] != "		NrOfLines	=") then goto check_next_line 
	goto get_rows_cols

	check_next_line:
	$line = $line + 1
  	goto flag_nroflines

# Parse the values for rows and columns from the original
# headers 'NrOfLines' and 'NrOfCellsPerLine' lines.

get_rows_cols:
	$col = $line + 1
	$rowline = split $billines[$line] at " "
	$rows = $rowline[2]
	$colline = split $billines[$col] at " "
	$cols = $colline[2]

rename_original_ers:
	$origfile = $bil_dataset + ".bak"
	$cmd = $copy_cmd + $bil_dataset + " " + $origfile

	say status "copying original ERS header to: " + $origfile + "\n"  
#	say status $cmd + "\n"  
	system $cmd

delete $bil_dataset
set output to $bil_dataset

$hlines = 1
say status "creating new classified ERS header: " + $bil_dataset + "\n"  

make_class_ers_part1:
println $billines[$hlines]
$hlines = $hlines + 1
if ($hlines < $total_lines) then goto make_class_ers_part1

$range = ($highval - $lowval)
$currval = $lowval
$curr_col = 0
$grey_step = (65534 / $range)
$grey_step = (floor($grey_step)) # round to integer if needed
$bandid = "Classified"
$allreg = "All"

# Generate the 'All' region block. (Not really needed, and
# cannot get the poly coords without some trouble, so we
# don't add them.)

println "		BandId Begin"
println "			Value		= \""+$bandid+"\""
println "		BandId End"
println "		RegionInfo Begin"
println "			Type		= Polygon"
println "			RegionName	= \""+$allreg+"\""
println "			SourceDataset	= \""+$bil_dataset+"\""
println "			SubRegion	= {"
println "			0	0"
println "			0	" + $rows
println "			" +$cols+ "      " +$rows
println "			" +$cols+ "	    0"
println "			}"
println "		RegionInfo End"

# Loop through and add a "RegionInfo" section for each class
# number we found, and increment the color value so we end up
# with a stepped greyscale color scheme for the classified 
# image for the default.

add_class_regions:
$regname = "Class " + $currval
if ($currval == $lowval) then goto start_RGB_zero  
$curr_col = $curr_col + $grey_step
goto generate_reg_blocks

	start_RGB_zero: # start at zero (black) if first class
	$curr_col = 0

generate_reg_blocks:
println "		RegionInfo Begin"
println "			Type		= Class"
println "			RegionName	= \""+$regname+"\""
println "			SourceDataset	= \""+$bil_dataset+"\""
println "			RGBcolour Begin"
println "				Red			= " +$curr_col
println "				Green		= " +$curr_col
println "				Blue		= " +$curr_col
println "			RGBcolour End"
println "			ClassNumber	= " +$currval
println "		RegionInfo End"
  
$currval = $currval + 1
if ($currval <= $highval) then goto add_class_regions 

println "	RasterInfo End"
println "DatasetHeader End"

set output to output window

# Check if they want to calc stats on the new header.

if ($calc_stats == 0) then goto check_display_image

say status "calculating stats for: "
say status $bil_dataset + "\n"
say status "please wait...\n"

$sys_command = "ersstats -s 1 " +  $bil_dataset
system $sys_command

# Check if they want to display the image. It will come up
# with the default greyscale color set we built.

check_display_image:

if ($show_image == 0) then goto wizard_cancel
 
say status "displaying classified image...\n"
	new algorithm
	set algorithm mode pseudo
	first surface
	set layer type to classdisplay
	set layer dataset to $bil_dataset
	set layer input 1 to band 1
	set transform type to hist

	new window
	copy algorithm to window
	go window

say status "finished...exiting.\n"

sleep 3
delete status

# Close the wizard and exit.
wizard_cancel:

wizard close
exit
