//?????????? ????????? "Derivativ" ??? 
//??????? ??????????? ?? ???????
//(c) 2002 ??????? ???????    v.  1.1 
//??????????? ??????? ???????    http://users.freenet.am/~askkur/
//
//"Derivativ" program realization for 
//calculating function derivative
//(c) 2002 Askanaz Kyureghyan  v. 1.1
//Programmer Askanaz Kyureghyan http://users.freenet.am/~askkur/

// DerivativDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Derivativ.h"
#include "DerivativDlg.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//++++++++++++++++++++++++++++++++++++++++++


CString Derivative_Func(CString Name,CString Argum)
{
   if (Name=="Sin"){return "Cos("+Argum+")";}
   if (Name=="Cos"){return "(-1)*Sin("+Argum+")";}
   if (Name=="Sh"){return "Ch("+Argum+")";}
   if (Name=="Ch"){return "Sh("+Argum+")";}
   if (Name=="Th"){return "1/(Ch("+Argum+")^2)";}
   if (Name=="Cth"){return "(-1)/(Sh("+Argum+")^2)";}

   return Name+"'("+Argum+")";
}
//////////////////////////////////////////////////////
void  ChageMinus(CString &Expr)
{
   int Par=0;
for(int i=0; i<Expr.GetLength(); i++)
{
   switch (Expr[i])
   {
   case'(':Par++;break;
   case')':Par--;break;
   case'-':if(Par==0){Expr.SetAt(i,'+');}break;
   case'+':if(Par==0){Expr.SetAt(i,'-');}break;
   }
}
}
//////////////////////////////////////////////////////
bool RmParenthesis(CString &Expr)
{
   if((Expr.GetLength()>2)&&
      (Expr[1]!='-') && (Expr[0]=='(')&& (Expr[Expr.GetLength()-1]==')'))
   {
      int i=1;
      int Par=1;
      while ((i<Expr.GetLength()-1)&&Par>0)
      {
         if (Expr[i]=='(') {Par++;}
         else 
         {
            if (Expr[i]==')') {Par--;}
         }
         i++;
      }
      if  (i==Expr.GetLength()-1)
      {
         Expr.Delete(0,1);
         Expr.Delete(Expr.GetLength()-1,1);
         return true;
      }
   }
   return false;
}
//////////////////////////////////////////////////////
int GetOperatorIndex(CString Expr,char Oper,CString &fX,CString &gX)
{
   int i=0;
   int Par=0;
   while (i<Expr.GetLength())
   {
      if (Expr[i]=='(') {Par++;}
      else 
      {
         if (Expr[i]==')') {Par--;}
         else
         {
            if ((Par==0)&&(Expr[i]==Oper))
            {
               fX=Expr;
               fX.Delete(i,Expr.GetLength()-i);
               RmParenthesis(fX);

               gX=Expr;
               gX.Delete(0,i+1);
               if ((RmParenthesis(gX))&&(Oper=='-')) {ChageMinus(gX);}
               return i;
            }
         }
      }
      i++;
   }
   return -1;
}
//////////////////////////////////////////////////////

char Derivative_Expr(CString Expr,CString &fX,CString &gX)
{
// Expr=fX +-/*^ gX
// Expr=Sin(fX)    gX=Sin   return fX
// Expr=fX
   CString TExpr=Expr;
   if (TExpr.GetLength()>1)
   {
      RmParenthesis(TExpr);
      if (TExpr.GetLength()>1)
      {
         if (GetOperatorIndex(TExpr,'+',fX,gX)!=(-1)){return '+';}
         if (GetOperatorIndex(TExpr,'-',fX,gX)!=(-1)){return '-';}
         if (GetOperatorIndex(TExpr,'*',fX,gX)!=(-1)){return '*';}
         if (GetOperatorIndex(TExpr,'/',fX,gX)!=(-1)){return '/';}
         if (GetOperatorIndex(TExpr,'^',fX,gX)!=(-1)){return '^';}
         if (TExpr[TExpr.GetLength()-1]==')') 
         {
            int NameIndex=TExpr.Find('(');
            fX=TExpr;
            fX.Delete(0,NameIndex+1);
            fX.Delete(fX.GetLength()-1,1);
            gX=TExpr;
            gX.Delete(NameIndex,TExpr.GetLength()-NameIndex);
            return 'f';
         }
      }
   }
   fX=TExpr;
   return 'X';
}
//////////////////////////////////////////////////////
CString SetParenthesis(CString Expr,char Oper)
{
   CString fX="";
   CString gX="";
   switch (Derivative_Expr(Expr,fX,gX))
   {
   case '+':
   case '-':if ((Oper!='-')&&(Oper!='+')){return "("+Expr+")";}
   case '*':
   case '/':if (Oper=='^'){return "("+Expr+")";};break;
   }
   return Expr;
}
//////////////////////////////////////////////////////
CString DisignOperation(CString Expr1,CString Expr2,char Oper)
{
   CString fX="";
   CString gX="";
   RmParenthesis(Expr1);
   RmParenthesis(Expr2);
   switch (Oper)
   {
   case '+':
      if(Expr1=="0"){return SetParenthesis(Expr2,Oper);}
      if(Expr2=="0"){return SetParenthesis(Expr1,Oper);}
      return SetParenthesis(Expr1,Oper)+Oper+SetParenthesis(Expr2,Oper);
   case '-':
      if((Expr1=="0")&&(Expr2=="0")){return "0";}
      if(Expr2=="0"){return SetParenthesis(Expr1,Oper);}
      if(Expr1=="0")
      {
         switch (Derivative_Expr(Expr2,fX,gX))
         {
         case'+':
         case'-':ChageMinus(Expr2);
         }
         return "-"+SetParenthesis(Expr2,Oper);
      }
      switch (Derivative_Expr(Expr2,fX,gX))
      {
      case'+':
      case'-':ChageMinus(Expr2);
      }
      return SetParenthesis(Expr1,Oper)+Oper+SetParenthesis(Expr2,Oper);

   case '*':
      if((Expr1=="0")||(Expr2=="0")){return "0";}
      if(Expr1=="1"){return SetParenthesis(Expr2,Oper);}
      if(Expr2=="1"){return SetParenthesis(Expr1,Oper);}
      return SetParenthesis(Expr1,Oper)+Oper+SetParenthesis(Expr2,Oper);
   case '/':
      if(Expr1=="0"){return "0";}
      if(Expr2=="1"){return SetParenthesis(Expr1,Oper);}
      return SetParenthesis(Expr1,Oper)+Oper+SetParenthesis(Expr2,Oper);
   case '^':
      if(Expr2=="0"){return "1";}
      if(Expr1=="0"){return "0";}
      return SetParenthesis(Expr1,Oper)+Oper+SetParenthesis(Expr2,Oper);
   }
   return SetParenthesis(Expr1,Oper)+Oper+SetParenthesis(Expr2,Oper);
}
//////////////////////////////////////////////////////
CString Derivative (CString Expr,CString Param)
{
   CString fX="";
   CString gX="";
   CString fX_="";
   CString gX_="";
   char operation=Derivative_Expr(Expr,fX,gX);
   if (operation!='X')
   {
      fX_=Derivative(fX,Param);
      gX_=Derivative(gX,Param);
   }
   switch (operation)
   {
//   +,-: fX_+operation+gX_
   case '+':
   case '-': return DisignOperation(fX_,gX_,operation);

//   *: fX_+"*"+gX+"+"+gX_+"*"+fX
   case '*': return DisignOperation(
      DisignOperation(fX_,gX,'*'),
      DisignOperation(gX_,fX,'*'),'+');

//      /: "("+fX_+"*"+gX+"-"+gX_+"*"+fX+")/"+gX+"^2";
   case '/':return DisignOperation(
      DisignOperation(fX_,gX,'*'),
        DisignOperation(
          DisignOperation(gX_,fX,'*'),
          DisignOperation(gX,"2",'^'),
        '/'),
      '-');

//   ^: "("+gX+")*("+fX+")^("+gX+"-1)*("+fX_+")+("+fX+")^("+gX+")*("+gX_+")*Ln("+fX+")";
   case '^': return  DisignOperation(
       DisignOperation(
             DisignOperation(gX,fX_,'*'),
             DisignOperation(
                fX,  
                DisignOperation(gX,"1",'-'),
             '^'),
       '*'),
       DisignOperation(
             DisignOperation(fX,gX,'^'),
             DisignOperation(gX_,"ln("+fX+")",'*'),
       '*'),
       '+');

//   Derivative_Func(gX,fX)+"*"+fX_;
   case 'f':return DisignOperation(Derivative_Func(gX,fX),fX_,'*');
   default : if (fX==Param) {return "1";} else {return "0";}
   }
}

//++++++++++++++++++++++++++++++++++++++++++
/////////////////////////////////////////////////////////////////////////////
// CDerivativDlg dialog

CDerivativDlg::CDerivativDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CDerivativDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CDerivativDlg)
	m_Edit1 = _T("");
	m_Edit2 = _T("");
	m_Edit3 = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CDerivativDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDerivativDlg)
	DDX_Text(pDX, IDC_EDIT1, m_Edit1);
	DDX_Text(pDX, IDC_EDIT2, m_Edit2);
	DDX_Text(pDX, IDC_EDIT3, m_Edit3);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CDerivativDlg, CDialog)
	//{{AFX_MSG_MAP(CDerivativDlg)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON1_Derivativ, OnBUTTON1Derivativ)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDerivativDlg message handlers

BOOL CDerivativDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CDerivativDlg::OnPaint() 
{
	//CClientDC *cDC = new CClientDC(this);
	
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}

	

}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CDerivativDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CDerivativDlg::OnBUTTON1Derivativ() 
{
	// TODO: Add your control notification handler code here
//	CDialog *pDL = new CDialog(this);

	CString str1, str2, str3;
		
	

UpdateData(true);

str1 = 	m_Edit1;

str3= 	m_Edit3;

str2 = Derivative(str1, str3);

m_Edit2 = str2;

UpdateData(false);

	
	
}
