/*
	境界抽出ユ−ティリティプログラム
	　境界線を微分により計算し2値デ−タに分離する｡
	
	［ＴＰＳＣ１６］用外部シェルプログラム
	
	Cre.      1993. 3.20  by Yahara
	Rev.1.0   1993. 3.20  by Yahara
*/

#define EGBSIZE		1536	// EGB用ワ−クサイズ
#define MOSSIZE		4096	// マウス用ワ−クサイズ
#define BOOL		int		// 論理判断の型宣言
#define TRUE		1		// 真
#define FALSE		0		// 偽
#define MENUPAGE	0		// メニュ−ペ−ジ番号
#define DRAWPAGE	1		// 描画ペ−ジ番号
#define SCREEN		3		// 画面モ−ド
#define DRAWWIDE	640		// 処理画面横サイズ
#define DRAWHIDE	480		// 処理画面縦サイズ


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <math.h>
#include <egb.h>
#include <mos.h>
#include <loader.h>			// コプロセス定義ファイル

char EGB_work[EGBSIZE];		// EGBワ−クエリア
char MOS_work[MOSSIZE];		// マウスワ−クエリア

char matrix[4][DRAWWIDE];

void MatrixInit()
{
	int i,j;
	int col;
	/* 初めの3ライン分のカラ−濃度をマトリックスをセットする */
	for(j=0;j<3;j++) {
		for(i=0;i<DRAWWIDE;i++) {
			EGB_point(EGB_work,0,i,j,&col);
			matrix[j][i] = col;
		}
	}
}

void NextMatrixSet(int y)
{
	int i;
	int col;
	/* スキャンするラインの2ライン後をカラ−濃度をセットする */
	for(i=0;i<DRAWWIDE;i++) {
		EGB_point(EGB_work,0,i,y+2,&col);
		matrix[3][i] = col;
	}
}

void Pset(int x,int y)
{
	struct { 	unsigned short int n;
				short int x,y; } par;
	/* EGBル−チンの呼び出し */
	par.n = 1;
	par.x = x; par.y = y;
	EGB_pset(EGB_work,(char *)&par);
}

void Differental(int x,int y)
{
	int h,v,p;
	
	h = abs(matrix[0][x+1]+matrix[1][x+1]+matrix[2][x+1]
			-matrix[0][x-1]-matrix[1][x-1]-matrix[2][x-1]);
	v = abs(matrix[2][x+1]+matrix[2][x+1]+matrix[2][x+1]
			-matrix[0][x-1]-matrix[0][x-1]-matrix[0][x-1]);
	p = h + v;
	if( p > 0x0f ) p = 0x0f;
	EGB_color(EGB_work,0,p);			// ドットの色を指定
	Pset(x,y);
}

void MatrixShift()
{
	/* マトリックバッファをシフトする */
	memmove(&matrix[0][0],&matrix[1][0],DRAWWIDE*3);
}

main()
{
	ADDRESS temp;
	int x,y;
	int ch,mx,my;
	
	/* 画面･マウスの初期化 */
	EGB_resolution(EGB_work,MENUPAGE,SCREEN|0x40);		// Page0 Init
	EGB_resolution(EGB_work,DRAWPAGE,SCREEN|0x40);		// Page1 Init
	EGB_displayPage(EGB_work,0,3);						// 2page view
	MOS_start(MOS_work,MOSSIZE);						// マウス初期化
	MOS_resolution(MENUPAGE,SCREEN);
	MOS_resolution(DRAWPAGE,SCREEN);
	
	EGB_writePage(EGB_work,DRAWPAGE);	// 描画ペ−ジを指定
	EGB_paintMode(EGB_work,0x22);		// ペイントモ−ドを指定
	
	/* 処理開始 */
	MatrixInit();
	for(y=1;y<DRAWHIDE-1;y++) {
		MOS_rdpos(&ch,&mx,&my);
		if( ch != 0 ) break;		// マウスが押されたら処理を中断
		NextMatrixSet(y);
		for(x=1;x<DRAWWIDE-1;x++)
			Differental(x,y);
		MatrixShift();
	}
	
	/* 子プロセスの終了処理 */
	MOS_end();
	pcl_get_dta(&temp);
	pcl_exit(0);
	return (0);
}
